/
happy-dom.ts
50 lines (44 loc) · 1.5 KB
/
happy-dom.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
import { importModule } from 'local-pkg'
import type { Environment } from '../../types'
import { populateGlobal } from './utils'
export default <Environment>({
name: 'happy-dom',
transformMode: 'web',
async setupVM({ happyDOM = {} }) {
const { Window } = await importModule('happy-dom') as typeof import('happy-dom')
const win = new Window({
...happyDOM,
url: happyDOM.url || 'http://localhost:3000',
}) as any
// TODO: browser doesn't expose Buffer, but a lot of dependencies use it
win.Buffer = Buffer
// inject structuredClone if it exists
if (typeof structuredClone !== 'undefined' && !win.structuredClone)
win.structuredClone = structuredClone
return {
getVmContext() {
return win
},
async teardown() {
await win.happyDOM.cancelAsync()
},
}
},
async setup(global, { happyDOM = {} }) {
// happy-dom v3 introduced a breaking change to Window, but
// provides GlobalWindow as a way to use previous behaviour
const { Window, GlobalWindow } = await importModule('happy-dom') as typeof import('happy-dom')
const win = new (GlobalWindow || Window)({
...happyDOM,
url: happyDOM.url || 'http://localhost:3000',
})
const { keys, originals } = populateGlobal(global, win, { bindFunctions: true })
return {
teardown(global) {
win.happyDOM.cancelAsync()
keys.forEach(key => delete global[key])
originals.forEach((v, k) => global[k] = v)
},
}
},
})