-
Notifications
You must be signed in to change notification settings - Fork 16
/
jest.setup.js
80 lines (72 loc) · 2.23 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
const { JSDOM } = require('jsdom');
const { TextDecoder, TextEncoder } = require('util');
const jsdom = new JSDOM(`<div id="main"></div>`, {
// https://github.com/jsdom/jsdom#basic-options
// 禁用掉 resources: usable, 采用 jsdom 默认策略不加载 subresources
// 避免测试用例加载 external subresource, 如 iconfont 的 css 挂掉
// resources: 'usable',
runScripts: 'dangerously',
url: 'http://localhost/?id=1',
});
global.document = jsdom.window.document;
let text = '';
global.navigator = Object.assign(jsdom.window.navigator, {
clipboard: {
writeText(value) {
text = value;
},
readText() {
return text;
},
},
});
global.Element = jsdom.window.Element;
global.HTMLDivElement = jsdom.window.HTMLDivElement;
global.fetch = jsdom.window.fetch;
global.location = jsdom.window.location;
global.getComputedStyle = jsdom.window.getComputedStyle;
global.window = jsdom.window;
global.DOMParser = jsdom.window.DOMParser;
global.HTMLDivElement = jsdom.window.HTMLDivElement;
global.MutationObserver = jsdom.window.MutationObserver;
global.requestAnimationFrame = (fn) => setTimeout(fn, 16);
jsdom.window.requestAnimationFrame = (fn) => setTimeout(fn, 16);
jsdom.window.cancelAnimationFrame = () => {};
global.document.queryCommandSupported = () => {};
global.document.execCommand = () => {};
global.HTMLElement = jsdom.window.HTMLElement;
global.self = global;
global.TextEncoder = TextEncoder;
global.TextDecoder = TextDecoder;
// https://jestjs.io/docs/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom
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(),
})),
});
class MockLocalStorage {
constructor() {
this.store = {};
}
clear() {
this.store = {};
}
getItem(key) {
return this.store[key] || null;
}
setItem(key, value) {
this.store[key] = value.toString();
}
removeItem(key) {
delete this.store[key];
}
}
global.localStorage = new MockLocalStorage();