-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathjestFrameworkSetup.js
More file actions
351 lines (309 loc) · 10.3 KB
/
Copy pathjestFrameworkSetup.js
File metadata and controls
351 lines (309 loc) · 10.3 KB
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
/* eslint-disable */
import 'jest-styled-components';
import snakeCase from 'snake-case';
import { toMatchSnapshot } from 'jest-snapshot';
import { configureToMatchImageSnapshot } from 'jest-image-snapshot';
import * as emotion from 'emotion';
import { createSerializer } from 'jest-emotion';
import 'jest-localstorage-mock';
let consoleError;
let consoleWarn;
let consoleLog;
// URL is not available for non Node environment
if (global.URL) {
global.URL.createObjectURL = () => 'mock result of URL.createObjectURL()';
global.URL.revokeObjectURL = () => 'mock result of URL.revokeObjectURL()';
}
if (!global.WEBSITE_ENV) {
global.WEBSITE_ENV = 'local';
}
// Node promise rejection are now logged for debbugging
process.on('unhandledRejection', reason => {
console.log('REJECTION', reason);
});
/*
This file is executed after the test framework is setup for each test file. Addons that modify
the `expect` object can be applied here.
@see https://facebook.github.io/jest/docs/configuration.html#setuptestframeworkscriptfile-string
*/
const pmModel = require('./node_modules/prosemirror-model');
const diff = require('./node_modules/jest-diff');
/**
* Polyfill DOMElement.innerText because JSDOM lacks support for it.
* @link https://github.com/tmpvar/jsdom/issues/1245
*/
/**
* We're checking the document actually exists here because tests using `jest-styled-components`
* need to be run with `testEnvironment=node` for `styled-components@^1`
* @see https://github.com/styled-components/jest-styled-components#styled-components--v2
*/
if (
typeof document !== 'undefined' &&
!('innerText' in document.createElement('a'))
) {
const getInnerText = node =>
Array.prototype.slice.call(node.childNodes).reduce((text, child) => {
if (child.nodeType === child.TEXT_NODE) {
return `${text}${child.textContent}`;
}
if (child.childNodes.length) {
return `${text}${getInnerText(child)}`;
}
return text;
}, '');
Object.defineProperty(HTMLElement.prototype, 'innerText', {
configurable: false,
enumerable: true,
get: function get() {
return getInnerText(this);
},
set: function set(text) {
const textNodes = Array.prototype.slice
.call(this.childNodes)
.filter(node => node.nodeType === node.TEXT_NODE);
// If there's only one child that is a text node, update it
if (textNodes.length === 1) {
textNodes[0].textContent = text;
return;
}
// Remove all child nodes as per WHATWG LS Spec
Array.prototype.slice
.call(this.childNodes)
.forEach(node => this.removeChild(node));
// Append a single text child node with the text
this.appendChild(this.ownerDocument.createTextNode(text));
},
});
}
/**
* We're checking the window actually exists here because tests using `jest-styled-components`
* need to be run with `testEnvironment=node` for `styled-components@^1`
* @see https://github.com/styled-components/jest-styled-components#styled-components--v2
*/
if (typeof window !== 'undefined' && !('cancelAnimationFrame' in window)) {
window.cancelAnimationFrame = () => {
if (!window.hasWarnedAboutCancelAnimationFramePolyfill) {
window.hasWarnedAboutCancelAnimationFramePolyfill = true;
console.warn(
'Warning! Test uses DOM cancelAnimationFrame API which is not available in JSDOM/Node environment.',
);
}
};
}
function transformDoc(fn) {
return doc => {
const walk = fn => node => {
const { content = [], ...rest } = node;
const transformedNode = fn(rest);
const walkWithFn = walk(fn);
if (content.length) {
transformedNode.content = content.map(walkWithFn);
}
return transformedNode;
};
return walk(fn)(doc);
};
}
const hasLocalId = type =>
type === 'status' ||
type === 'taskItem' ||
type === 'taskList' ||
type === 'decisionItem' ||
type === 'decisionList';
const removeIdsFromDoc = transformDoc(node => {
/**
* Replace `id` of media nodes with a fixed id
* @see https://regex101.com/r/FrYUen/1
*/
if (node.type === 'media') {
const replacedNode = {
...node,
attrs: {
...node.attrs,
id: node.attrs.id.replace(
/(temporary:)?([a-z0-9\-]+)(:.*)?$/,
'$11234-5678-abcd-efgh$3',
),
__fileName: 'example.png',
},
};
if (node.attrs.__key) {
replacedNode.attrs.__key = node.attrs.__key.replace(
/(temporary:)?([a-z0-9\-]+)(:.*)?$/,
'$11234-5678-abcd-efgh$3',
);
}
return replacedNode;
}
if (hasLocalId(node.type)) {
return {
...node,
attrs: {
...node.attrs,
localId: node.attrs.localId.replace(/([a-z0-9\-]+)/, () => 'abc-123'),
},
};
}
return node;
});
/* eslint-disable no-undef */
expect.extend({
toEqualDocument(actual, expected) {
// Because schema is created dynamically, expected value is a function (schema) => PMNode;
// That's why this magic is necessary. It simplifies writing assertions, so
// instead of expect(doc).toEqualDocument(doc(p())(schema)) we can just do:
// expect(doc).toEqualDocument(doc(p())).
//
// Also it fixes issues that happens sometimes when actual schema and expected schema
// are different objects, making this case impossible by always using actual schema to create expected node.
expected =
typeof expected === 'function' && actual.type && actual.type.schema
? expected(actual.type.schema)
: expected;
if (
!(expected instanceof pmModel.Node) ||
!(actual instanceof pmModel.Node)
) {
return {
pass: false,
actual,
expected,
name: 'toEqualDocument',
message:
'Expected both values to be instance of prosemirror-model Node.',
};
}
if (expected.type.schema !== actual.type.schema) {
return {
pass: false,
actual,
expected,
name: 'toEqualDocument',
message: 'Expected both values to be using the same schema.',
};
}
const pass = this.equals(actual.toJSON(), expected.toJSON());
const message = pass
? () =>
`${this.utils.matcherHint('.not.toEqualDocument')}\n\n` +
`Expected JSON value of document to not equal:\n ${this.utils.printExpected(
expected,
)}\n` +
`Actual JSON:\n ${this.utils.printReceived(actual)}`
: () => {
const diffString = diff(expected, actual, {
expand: this.expand,
});
return (
`${this.utils.matcherHint('.toEqualDocument')}\n\n` +
`Expected JSON value of document to equal:\n${this.utils.printExpected(
expected,
)}\n` +
`Actual JSON:\n ${this.utils.printReceived(actual)}` +
`${diffString ? `\n\nDifference:\n\n${diffString}` : ''}`
);
};
return {
pass,
actual,
expected,
message,
name: 'toEqualDocument',
};
},
toMatchDocSnapshot(actual) {
const { currentTestName, snapshotState } = this;
const removeFirstWord = sentence =>
sentence
.split(' ')
.slice(1)
.join(' ');
// this change is to ensure we are mentioning test file name only once in snapshot file
// for integration tests only
const newTestName = removeFirstWord(currentTestName);
// remove ids that may change from the document so snapshots are repeatable
const transformedDoc = removeIdsFromDoc(actual);
// since the test runner fires off multiple browsers for a single test, map each snapshot to the same one
// (otherwise we'll try to create as many snapshots as there are browsers)
const oldCounters = snapshotState._counters;
snapshotState._counters = Object.create(oldCounters, {
set: {
value: key => oldCounters.set(key, 1),
},
get: {
value: key => oldCounters.get(key),
},
});
// In `jest-snapshot@22`, passing the optional testName doesn't override test name anymore.
// Instead it appends the passed name with original name.
const oldTestName = this.currentTestName;
this.currentTestName = newTestName;
const ret = toMatchSnapshot.call(this, transformedDoc);
this.currentTestName = oldTestName;
return ret;
},
});
// Copied from react-beautiful-dnd/test/setup.js
if (typeof document !== 'undefined') {
// overriding these properties in jsdom to allow them to be controlled
Object.defineProperties(document.documentElement, {
clientWidth: {
writable: true,
value: document.documentElement.clientWidth,
},
clientHeight: {
writable: true,
value: document.documentElement.clientHeight,
},
scrollWidth: {
writable: true,
value: document.documentElement.scrollWidth,
},
scrollHeight: {
writable: true,
value: document.documentElement.scrollHeight,
},
});
}
// Setting initial viewport
// Need to set clientWidth and clientHeight as jsdom does not set these properties
if (typeof document !== 'undefined' && typeof window !== 'undefined') {
document.documentElement.clientWidth = window.innerWidth;
document.documentElement.clientHeight = window.innerHeight;
}
if (process.env.CI) {
beforeEach(() => {
consoleError = console.error;
consoleWarn = console.warn;
consoleLog = console.log;
console.error = jest.fn();
console.warn = jest.fn();
console.log = jest.fn();
});
afterEach(() => {
console.error = consoleError;
console.warn = consoleWarn;
console.log = consoleLog;
});
}
expect.addSnapshotSerializer(createSerializer(emotion));
// set up for visual regression
if (process.env.VISUAL_REGRESSION) {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 600000;
beforeAll(async () => {
global.page = await global.browser.newPage();
}, jasmine.DEFAULT_TIMEOUT_INTERVAL);
afterAll(async () => {
await global.page.close();
await global.browser.disconnect();
});
// A failureThreshold of 1 will pass tests that have > 2 percent failing pixels
const customConfig = { threshold: 0.0 };
const toMatchProdImageSnapshot = configureToMatchImageSnapshot({
customDiffConfig: customConfig,
failureThreshold: '20',
failureThresholdType: 'pixel',
noColors: true,
});
expect.extend({ toMatchProdImageSnapshot });
}