This repository is currently being migrated. It's locked while the migration is in progress.
forked from Nanciee/cypress-autorecord
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
264 lines (231 loc) · 9.09 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
'use strict';
const path = require('path');
const util = require('./util');
const guidGenerator = util.guidGenerator;
const sizeInMbytes = util.sizeInMbytes;
const cypressConfig = Cypress.config('autorecord') || {};
const isCleanMocks = cypressConfig.cleanMocks || false;
const isForceRecord = cypressConfig.forceRecord || false;
const recordTests = cypressConfig.recordTests || [];
const blacklistRoutes = cypressConfig.blacklistRoutes || [];
const whitelistHeaders = cypressConfig.whitelistHeaders || [];
const supportedMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD'];
const fileName = path.basename(
Cypress.spec.name,
path.extname(Cypress.spec.name),
);
// The replace fixes Windows path handling
const fixturesFolder = Cypress.config('fixturesFolder').replace(/\\/g, '/');
const mocksFolder = path.join(fixturesFolder, '../mocks');
before(function () {
if (isCleanMocks) {
cy.task('cleanMocks');
}
if (isForceRecord) {
cy.task('removeAllMocks');
}
});
module.exports = function autoRecord() {
const whitelistHeaderRegexes = whitelistHeaders.map(str => RegExp(str));
// For cleaning, to store the test names that are active per file
let testNames = [];
// For cleaning, to store the clean mocks per file
let cleanMockData = {};
// Locally stores all mock data for this spec file
let routesByTestId = {};
// For recording, stores data recorded from hitting the real endpoints
let routes = [];
// Stores any fixtures that need to be added
let addFixture = {};
// Stores any fixtures that need to be removed
let removeFixture = [];
// For force recording, check to see if [r] is present in the test title
let isTestForceRecord = false;
before(function () {
// Get mock data that relates to this spec file
cy.task('readFile', path.join(mocksFolder, `${fileName}.json`)).then(data => {
routesByTestId = data === null ? {} : data;
});
});
beforeEach(function () {
// Reset routes before each test case
routes = [];
cy.server({
// Filter out blacklisted routes from being recorded and logged
whitelist: xhr => {
if (xhr.url) {
// TODO: Use blobs
return blacklistRoutes.some(route => xhr.url.includes(route));
}
},
// Here we handle all requests passing through Cypress' server
onResponse: response => {
const url = response.url;
const status = response.status;
const method = response.method;
let responseBody = response.response.body;
let data = responseBody;
let body = response.request.body;
let assignValueAndResolvePromise = (parsedData) => {
data = parsedData;
Promise.resolve();
}
// Pushes a new entry into the routes array if it's not a duplicate
let pushRoute = (url, method, status, data, body) => {
if (!routes.some(route => route.url === url && route.body === body && route.method === method)) {
// Only collect headers if this is not a duplicate
const headers = Object.entries(response.response.headers)
.filter(([key]) => whitelistHeaderRegexes.some(regex => regex.test(key)))
.reduce((obj, [key, value]) => ({ ...obj, [key]: value }), {});
routes.push({ url, method, status, data, body, headers });
}
};
// Checking if body contains Blob that needs parsing to support fetch polyfill
if (responseBody && responseBody.constructor && responseBody.constructor.name == "Blob") {
let bodyParsingPromise;
if (responseBody.type == "application/json") {
bodyParsingPromise = new Response(responseBody).json().then(assignValueAndResolvePromise);
} else if (responseBody.type == "text/plain") {
bodyParsingPromise = new Response(responseBody).text().then(assignValueAndResolvePromise);
}
// checking if we needed to parce body
if (bodyParsingPromise) {
bodyParsingPromise.then(() => {
pushRoute(url, method, status, data, body);
})
} else {
pushRoute(url, method, status, data, body);
}
} else {
pushRoute(url, method, status, data, body);
}
},
// Disable all routes that are not mocked
force404: true,
});
// check to see if test is being force recorded
// TODO: change this to regex so it only reads from the beginning of the string
isTestForceRecord = this.currentTest.title.includes('[r]');
this.currentTest.title = isTestForceRecord ? this.currentTest.title.split('[r]')[1].trim() : this.currentTest.title;
// Load stubbed data from local JSON file
// Do not stub if...
// This test is being force recorded
// there are no mock data for this test
if (
!recordTests.includes(this.currentTest.title)
&& !isTestForceRecord
&& routesByTestId[this.currentTest.title]
) {
// This is used to group routes by method type and url (e.g. { GET: { '/api/messages': {...} }})
const sortedRoutes = {};
supportedMethods.forEach(method => {
sortedRoutes[method] = {};
});
cy.server({
force404: true,
});
routesByTestId[this.currentTest.title].forEach((request) => {
if (!sortedRoutes[request.method][request.url]) {
sortedRoutes[request.method][request.url] = [];
}
sortedRoutes[request.method][request.url].push(request);
});
const onResponse = (method, url, index) => {
if (sortedRoutes[method][url].length > index) {
const response = sortedRoutes[method][url][index];
cy.route({
method: response.method,
url: url,
status: response.status,
headers: response.headers,
response: response.fixtureId ? `fixture:${response.fixtureId}.json` : response.response,
// This handles requests from the same url but with different request bodies
onResponse: () => onResponse(method, url, index + 1),
});
}
};
// Stub all recorded routes
Object.keys(sortedRoutes).forEach(method => {
Object.keys(sortedRoutes[method]).forEach(url => onResponse(method, url, 0))
});
} else {
// Allow all routes to go through
cy.server({ force404: false });
// This tells Cypress to hook into all types of requests
supportedMethods.forEach(method => {
cy.route({
method,
url: '*',
});
});
}
// Store test name if isCleanMocks is true
if (isCleanMocks) {
testNames.push(this.currentTest.title);
}
});
afterEach(function () {
// Check to see if the current test already has mock data or if forceRecord is on
if (
(!routesByTestId[this.currentTest.title]
|| isTestForceRecord
|| recordTests.includes(this.currentTest.title))
&& !isCleanMocks
) {
// Construct endpoint to be saved locally
const endpoints = routes.map((request) => {
// Check to see of mock data is too large for request header
const isFileOversized = sizeInMbytes(request.data) > 70;
let fixtureId;
// If the mock data is too large, store it in a separate json
if (isFileOversized) {
fixtureId = guidGenerator();
addFixture[path.join(fixturesFolder, `${fixtureId}.json`)] = request.data;
}
return {
fixtureId: fixtureId,
url: request.url,
method: request.method,
status: request.status,
headers: request.headers,
body: request.body,
response: isFileOversized ? undefined : request.data,
};
});
// Delete fixtures if we are overwriting mock data
if (routesByTestId[this.currentTest.title]) {
routesByTestId[this.currentTest.title].forEach((route) => {
// If fixtureId exist, delete the json
if (route.fixtureId) {
removeFixture.push(path.join(fixturesFolder, `${route.fixtureId}.json`));
}
});
}
// Store the endpoint for this test in the mock data object for this file if there are endpoints for this test
if (endpoints.length > 0) {
routesByTestId[this.currentTest.title] = endpoints;
}
}
});
after(function () {
// Transfer used mock data to new object to be stored locally
if (isCleanMocks) {
Object.keys(routesByTestId).forEach((testName) => {
if (testNames.includes(testName)) {
cleanMockData[testName] = routesByTestId[testName];
} else {
routesByTestId[testName].forEach((route) => {
if (route.fixtureId) {
cy.task('deleteFile', path.join(fixturesFolder, `${route.fixtureId}.json`));
}
});
}
});
}
removeFixture.forEach(fixtureName => cy.task('deleteFile', fixtureName));
cy.writeFile(path.join(mocksFolder, `${fileName}.json`), isCleanMocks ? cleanMockData : routesByTestId);
Object.keys(addFixture).forEach(fixtureName => {
cy.writeFile(fixtureName, addFixture[fixtureName]);
});
});
};