-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathjest.setup.js
More file actions
273 lines (256 loc) · 7.63 KB
/
jest.setup.js
File metadata and controls
273 lines (256 loc) · 7.63 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
// React 18 + React Testing Library setup
// Global jest-dom matchers (Jest 29+ supports this properly!)
// This means we don't need to import '@testing-library/jest-dom' in each test file
import '@testing-library/jest-dom';
// Polyfill TextEncoder/TextDecoder for Jest 29 + jsdom
// Required for slate-html-serializer and other packages using encoding APIs
import { TextEncoder, TextDecoder } from 'util';
global.TextEncoder = TextEncoder;
global.TextDecoder = TextDecoder;
// Mock window.matchMedia (required for MUI components)
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation((query) => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // deprecated
removeListener: jest.fn(), // deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});
// Mock ResizeObserver (required for many modern components)
global.ResizeObserver = class ResizeObserver {
constructor(callback) {
this.callback = callback;
}
observe() {}
unobserve() {}
disconnect() {}
};
// Mock IntersectionObserver (may be needed by some components)
global.IntersectionObserver = class IntersectionObserver {
constructor(callback) {
this.callback = callback;
}
observe() {
return null;
}
unobserve() {
return null;
}
disconnect() {
return null;
}
takeRecords() {
return [];
}
};
// Mock MutationObserver (required for components that observe DOM changes)
global.MutationObserver = class MutationObserver {
constructor(callback) {
this.callback = callback;
}
observe() {
return null;
}
disconnect() {
return null;
}
takeRecords() {
return [];
}
};
// Mock scrollIntoView (not implemented in jsdom)
if (!Element.prototype.scrollIntoView) {
Element.prototype.scrollIntoView = jest.fn();
}
// Mock createRange (required for @testing-library/user-event)
if (!document.createRange) {
document.createRange = () => ({
setStart: () => {},
setEnd: () => {},
commonAncestorContainer: {
nodeName: 'BODY',
ownerDocument: document,
},
cloneContents: () => document.createDocumentFragment(),
cloneRange: () => document.createRange(),
collapse: () => {},
compareBoundaryPoints: () => 0,
comparePoint: () => 0,
createContextualFragment: (html) => {
const div = document.createElement('div');
div.innerHTML = html;
return div.childNodes[0];
},
deleteContents: () => {},
detach: () => {},
extractContents: () => document.createDocumentFragment(),
getBoundingClientRect: () => ({
x: 0,
y: 0,
width: 0,
height: 0,
top: 0,
right: 0,
bottom: 0,
left: 0,
}),
getClientRects: () => [],
insertNode: () => {},
intersectsNode: () => true,
isPointInRange: () => false,
selectNode: () => {},
selectNodeContents: () => {},
setEndAfter: () => {},
setEndBefore: () => {},
setStartAfter: () => {},
setStartBefore: () => {},
surroundContents: () => {},
toString: () => '',
});
}
// Mock getSelection (required for @testing-library/user-event)
if (!document.getSelection) {
document.getSelection = () => ({
addRange: () => {},
removeAllRanges: () => {},
removeRange: () => {},
getRangeAt: () => document.createRange(),
toString: () => '',
rangeCount: 0,
isCollapsed: true,
type: 'None',
anchorNode: null,
anchorOffset: 0,
focusNode: null,
focusOffset: 0,
});
}
// Mock XMLHttpRequest for speech-rule-engine locale loading
// This prevents errors when speech-rule-engine tries to load locale files
const originalXHR = global.XMLHttpRequest;
global.XMLHttpRequest = class XMLHttpRequestMock extends originalXHR {
constructor() {
super();
// Ensure document and URL are available
if (!this._ownerDocument) {
Object.defineProperty(this, '_ownerDocument', {
value: { URL: 'http://localhost' },
writable: true,
});
}
}
open(method, url) {
// Prevent loading external locale files in tests
if (url && url.includes('/locales/')) {
this.mockResponse = true;
return;
}
try {
return super.open(method, url);
} catch (e) {
// Swallow errors for locale file loading
this.mockResponse = true;
}
}
send() {
if (this.mockResponse) {
// Mock successful empty response for locale files
setTimeout(() => {
Object.defineProperty(this, 'status', { value: 200 });
Object.defineProperty(this, 'response', { value: '{}' });
Object.defineProperty(this, 'responseText', { value: '{}' });
if (this.onload) this.onload();
}, 0);
return;
}
try {
return super.send();
} catch (e) {
// Swallow errors
}
}
};
// Mock HTMLCanvasElement for Konva (required for canvas rendering in tests)
if (!HTMLCanvasElement.prototype.getContext) {
HTMLCanvasElement.prototype.getContext = () => ({
fillRect: jest.fn(),
clearRect: jest.fn(),
getImageData: jest.fn(() => ({ data: [] })),
putImageData: jest.fn(),
createImageData: jest.fn(() => []),
setTransform: jest.fn(),
drawImage: jest.fn(),
save: jest.fn(),
fillText: jest.fn(),
restore: jest.fn(),
beginPath: jest.fn(),
moveTo: jest.fn(),
lineTo: jest.fn(),
closePath: jest.fn(),
stroke: jest.fn(),
translate: jest.fn(),
scale: jest.fn(),
rotate: jest.fn(),
arc: jest.fn(),
fill: jest.fn(),
measureText: jest.fn(() => ({ width: 0 })),
transform: jest.fn(),
rect: jest.fn(),
clip: jest.fn(),
});
}
// Mock canvas package for Konva (Konva tries to require it in Node environment)
jest.mock('canvas', () => ({}), { virtual: true });
// Ensure customElements is available (jsdom provides this, but ensure it's there)
// Don't mock it - we need the real implementation for custom element registration
if (!global.customElements) {
// This should not happen in jsdom, but provide a fallback just in case
const registry = new Map();
global.customElements = {
define: (name, constructor) => {
if (registry.has(name)) {
throw new DOMException(`Failed to execute 'define' on 'CustomElementRegistry': the name "${name}" has already been used with this registry`);
}
registry.set(name, constructor);
},
get: (name) => registry.get(name),
whenDefined: (name) => {
if (registry.has(name)) {
return Promise.resolve(registry.get(name));
}
return Promise.resolve();
},
};
}
// Mock CustomEvent for custom element events
if (!global.CustomEvent) {
global.CustomEvent = class CustomEvent {};
}
// Suppress console errors/warnings in tests (optional - comment out if you want to see them)
const originalError = console.error;
const originalWarn = console.warn;
beforeAll(() => {
console.error = jest.fn((...args) => {
// Suppress React key prop warnings
if (typeof args[0] === 'string' && args[0].includes('Warning:')) return;
if (typeof args[0] === 'string' && args[0].includes('Each child in a list should have a unique "key" prop')) return;
// Suppress MUI warnings about using deprecated props
if (typeof args[0] === 'string' && args[0].includes('MUI:')) return;
originalError.call(console, ...args);
});
console.warn = jest.fn((...args) => {
// Suppress specific warnings if needed
if (typeof args[0] === 'string' && args[0].includes('Warning:')) return;
if (typeof args[0] === 'string' && args[0].includes('MUI:')) return;
originalWarn.call(console, ...args);
});
});
afterAll(() => {
console.error = originalError;
console.warn = originalWarn;
});