/
jsdom.ts
56 lines (52 loc) · 1.52 KB
/
jsdom.ts
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
import { importModule } from 'local-pkg'
import type { Environment, JSDOMOptions } from '../../types'
import { populateGlobal } from './utils'
export default <Environment>({
name: 'jsdom',
async setup(global, { jsdom = {} }) {
const {
CookieJar,
JSDOM,
ResourceLoader,
VirtualConsole,
} = await importModule('jsdom') as typeof import('jsdom')
const {
html = '<!DOCTYPE html>',
userAgent,
url = 'http://localhost:3000',
contentType = 'text/html',
pretendToBeVisual = true,
includeNodeLocations = false,
runScripts = 'dangerously',
resources,
console = false,
cookieJar = false,
...restOptions
} = jsdom as JSDOMOptions
const dom = new JSDOM(
html,
{
pretendToBeVisual,
resources: resources ?? (userAgent ? new ResourceLoader({ userAgent }) : undefined),
runScripts,
url,
virtualConsole: console && global.console ? new VirtualConsole().sendTo(global.console) : undefined,
cookieJar: cookieJar ? new CookieJar() : undefined,
includeNodeLocations,
contentType,
userAgent,
...restOptions,
},
)
const { keys, allowRewrite } = populateGlobal(global, dom.window)
const originals = new Map<string | symbol, any>(
allowRewrite.map(([key]) => [key, global[key]]),
)
return {
teardown(global) {
keys.forEach(key => delete global[key])
originals.forEach((v, k) => global[k] = v)
},
}
},
})