forked from instructure/canvas-lms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjest-setup.js
321 lines (285 loc) · 9.07 KB
/
jest-setup.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
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
/*
* Copyright (C) 2018 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'cross-fetch/polyfill'
import {TextDecoder, TextEncoder} from 'util'
import CoreTranslations from '../public/javascripts/translations/en.json'
import Enzyme from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
import filterUselessConsoleMessages from '@instructure/filter-console-messages'
import rceFormatMessage from '@instructure/canvas-rce/es/format-message'
import {up as configureDateTime} from '@canvas/datetime/configureDateTime'
import {up as configureDateTimeMomentParser} from '@canvas/datetime/configureDateTimeMomentParser'
import {up as installNodeDecorations} from '../ui/boot/initializers/installNodeDecorations'
import {useTranslations} from '@canvas/i18n'
import MockBroadcastChannel from './MockBroadcastChannel'
useTranslations('en', CoreTranslations)
rceFormatMessage.setup({
locale: 'en',
missingTranslation: 'ignore',
})
/**
* We want to ensure errors and warnings get appropriate eyes. If
* you are seeing an exception from here, it probably means you
* have an unintended consequence from your changes. If you expect
* the warning/error, add it to the ignore list below.
*/
/* eslint-disable no-console */
const globalError = global.console.error
const ignoredErrors = [
/An update to %s inside a test was not wrapped in act/,
/Can't perform a React state update on an unmounted component/,
/Function components cannot be given refs/,
/Invalid prop `heading` of type `object` supplied to `Billboard`/, // https://instructure.atlassian.net/browse/QUIZ-8870
/Invariant Violation/, // https://instructure.atlassian.net/browse/VICE-3968
/Prop `children` should be supplied unless/, // https://instructure.atlassian.net/browse/FOO-3407
/The above error occurred in the <.*> component/,
/You seem to have overlapping act\(\) calls/,
/Warning: `value` prop on `%s` should not be null. Consider using an empty string to clear the component or `undefined` for uncontrolled components.%s/,
/Warning: This synthetic event is reused for performance reasons/,
/Invalid prop `value` supplied to `MenuItem`/, // https://instructure.atlassian.net/browse/INSTUI-4054
]
const globalWarn = global.console.warn
const ignoredWarnings = [
/JQMIGRATE:/, // ignore warnings about jquery migrate; these are muted globally when not in a jest test
/componentWillReceiveProps/, // ignore warnings about componentWillReceiveProps; this method is deprecated and will be removed with react upgrades
]
global.console = {
log: console.log,
error: (error, ...rest) => {
if (
ignoredErrors.some(regex => regex.test(error)) ||
ignoredErrors.some(regex => regex.test(rest))
) {
return
}
globalError(error)
throw new Error(
`Looks like you have an unhandled error. Keep our test logs clean by handling or filtering it. ${error}`
)
},
warn: warning => {
if (ignoredWarnings.some(regex => regex.test(warning))) {
return
}
globalWarn(warning)
throw new Error(
`Looks like you have an unhandled warning. Keep our test logs clean by handling or filtering it. ${warning}`
)
},
info: console.info,
debug: console.debug,
}
/* eslint-enable no-console */
filterUselessConsoleMessages(global.console)
window.scroll = () => {}
window.ENV = {
use_rce_enhancements: true,
FEATURES: {
extended_submission_state: true,
},
}
Enzyme.configure({adapter: new Adapter()})
// because InstUI themeable components need an explicit "dir" attribute on the <html> element
document.documentElement.setAttribute('dir', 'ltr')
configureDateTime()
configureDateTimeMomentParser()
installNodeDecorations()
// because everyone implements `flat()` and `flatMap()` except JSDOM 🤦🏼♂️
if (!Array.prototype.flat) {
// eslint-disable-next-line no-extend-native
Object.defineProperty(Array.prototype, 'flat', {
configurable: true,
value: function flat(depth = 1) {
if (depth === 0) return this.slice()
return this.reduce(function (acc, cur) {
if (Array.isArray(cur)) {
acc.push(...flat.call(cur, depth - 1))
} else {
acc.push(cur)
}
return acc
}, [])
},
writable: true,
})
}
if (!Array.prototype.flatMap) {
// eslint-disable-next-line no-extend-native
Object.defineProperty(Array.prototype, 'flatMap', {
configurable: true,
value: function flatMap(_cb) {
return Array.prototype.map.apply(this, arguments).flat()
},
writable: true,
})
}
require('@instructure/ui-themes')
// set up mocks for native APIs
if (!('alert' in window)) {
window.alert = () => {}
}
if (!('MutationObserver' in window)) {
Object.defineProperty(window, 'MutationObserver', {
value: require('@sheerun/mutationobserver-shim'),
})
}
if (!('IntersectionObserver' in window)) {
Object.defineProperty(window, 'IntersectionObserver', {
writable: true,
configurable: true,
value: class IntersectionObserver {
disconnect() {
return null
}
observe() {
return null
}
takeRecords() {
return null
}
unobserve() {
return null
}
},
})
}
if (!('ResizeObserver' in window)) {
Object.defineProperty(window, 'ResizeObserver', {
writable: true,
configurable: true,
value: class IntersectionObserver {
observe() {
return null
}
unobserve() {
return null
}
disconnect() {
return null
}
},
})
}
if (!('matchMedia' in window)) {
window.matchMedia = () => ({
matches: false,
addListener: () => {},
removeListener: () => {},
})
window.matchMedia._mocked = true
}
global.BroadcastChannel = global.BroadcastChannel || MockBroadcastChannel
global.DataTransferItem = global.DataTransferItem || class DataTransferItem {}
global.performance = global.performance || {}
global.performance.getEntriesByType = global.performance.getEntriesByType || (() => [])
if (!('scrollIntoView' in window.HTMLElement.prototype)) {
window.HTMLElement.prototype.scrollIntoView = () => {}
}
// Suppress errors for APIs that exist in JSDOM but aren't implemented
Object.defineProperty(window, 'scrollTo', {
configurable: true,
writable: true,
value: () => {},
})
const locationProperties = Object.getOwnPropertyDescriptors(window.location)
Object.defineProperty(window, 'location', {
configurable: true,
enumerable: true,
get: () =>
Object.defineProperties(
{},
{
...locationProperties,
href: {
...locationProperties.href,
// Prevents JSDOM errors from doing window.location.href = ...
set: () => {},
},
reload: {
configurable: true,
enumerable: true,
writeable: true,
// Prevents JSDOM errors from doing window.location.reload()
value: () => {},
},
}
),
// Prevents JSDOM errors from doing window.location = ...
set: () => {},
})
if (!('structuredClone' in window)) {
Object.defineProperty(window, 'structuredClone', {
value: obj => JSON.parse(JSON.stringify(obj)),
})
}
if (typeof window.URL.createObjectURL === 'undefined') {
Object.defineProperty(window.URL, 'createObjectURL', {value: () => 'http://example.com/whatever'})
}
if (typeof window.URL.revokeObjectURL === 'undefined') {
Object.defineProperty(window.URL, 'revokeObjectURL', {value: () => undefined})
}
global.fetch =
global.fetch || jest.fn().mockImplementation(() => Promise.resolve({json: () => ({})}))
Document.prototype.createRange =
Document.prototype.createRange ||
function () {
return {
setEnd() {},
setStart() {},
getBoundingClientRect() {
return {right: 0}
},
getClientRects() {
return {
length: 0,
left: 0,
right: 0,
}
},
}
}
global.TextEncoder = TextEncoder
global.TextDecoder = TextDecoder
if (!('Worker' in window)) {
Object.defineProperty(window, 'Worker', {
value: class Worker {
constructor() {
this.postMessage = () => {}
this.terminate = () => {}
this.addEventListener = () => {}
this.removeEventListener = () => {}
this.dispatchEvent = () => {}
}
},
})
}
if (!Range.prototype.getBoundingClientRect) {
Range.prototype.getBoundingClientRect = () => ({
bottom: 0,
height: 0,
left: 0,
right: 0,
top: 0,
width: 0,
})
Range.prototype.getClientRects = () => ({
item: () => null,
length: 0,
[Symbol.iterator]: jest.fn(),
})
}