-
Notifications
You must be signed in to change notification settings - Fork 83
/
index.ts
158 lines (137 loc) · 4.62 KB
/
index.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
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
import type { Environment } from 'vitest/environments'
import { createFetch } from 'ofetch'
import { indexedDB } from 'fake-indexeddb'
import { joinURL } from 'ufo'
import { createApp, defineEventHandler, toNodeListener } from 'h3'
import defu from 'defu'
import { createRouter as createRadixRouter, exportMatcher, toRouteMatcher } from 'radix3'
import { populateGlobal } from 'vitest/environments'
import { createCall, createFetch as createLocalFetch } from 'unenv/runtime/fetch/index'
import type { NuxtBuiltinEnvironment } from './types'
import happyDom from './env/happy-dom'
import jsdom from './env/jsdom'
const environmentMap = {
'happy-dom': happyDom,
jsdom,
}
export default <Environment>{
name: 'nuxt',
transformMode: 'web',
async setup(global, environmentOptions) {
const url = joinURL(environmentOptions?.nuxt.url ?? 'http://localhost:3000',
environmentOptions?.nuxtRuntimeConfig.app?.baseURL || '/',
)
const environmentName = environmentOptions.nuxt.domEnvironment as NuxtBuiltinEnvironment
const environment = environmentMap[environmentName] || environmentMap['happy-dom']
const { window: win, teardown } = await environment(global, defu(environmentOptions, {
happyDom: { url },
jsdom: { url },
}))
win.__NUXT_VITEST_ENVIRONMENT__ = true
win.__NUXT__ = {
serverRendered: false,
config: {
public: {},
app: { baseURL: '/' },
...environmentOptions?.nuxtRuntimeConfig,
},
data: {},
state: {},
}
const app = win.document.createElement('div')
// this is a workaround for a happy-dom bug with ids beginning with _
app.id = environmentOptions.nuxt.rootId
win.document.body.appendChild(app)
if (environmentOptions?.nuxt?.mock?.intersectionObserver) {
win.IntersectionObserver
= win.IntersectionObserver
|| class IntersectionObserver {
observe() {}
unobserve() {}
disconnect() {}
}
}
if (environmentOptions?.nuxt?.mock?.indexedDb) {
// @ts-expect-error win.indexedDB is read-only
win.indexedDB = indexedDB
}
const h3App = createApp()
if (!win.fetch) {
await import('node-fetch-native/polyfill')
// @ts-expect-error URLSearchParams is not a proeprty of window
win.URLSearchParams = globalThis.URLSearchParams
}
// @ts-expect-error TODO: fix in h3
const localCall = createCall(toNodeListener(h3App))
const localFetch = createLocalFetch(localCall, win.fetch)
const registry = new Set<string>()
win.fetch = (init, options) => {
if (typeof init === 'string') {
const base = init.split('?')[0]
if (registry.has(base) || registry.has(init)) {
init = '/_' + init
}
}
return localFetch(init.toString(), {
...options,
headers: Array.isArray(options?.headers) ? new Headers(options?.headers) : options?.headers,
})
}
// @ts-expect-error fetch types differ slightly
win.$fetch = createFetch({ fetch: win.fetch, Headers: win.Headers })
win.__registry = registry
win.__app = h3App
const { keys, originals } = populateGlobal(global, win, {
bindFunctions: true,
})
// App manifest support
const timestamp = Date.now()
const routeRulesMatcher = toRouteMatcher(
createRadixRouter({ routes: environmentOptions.nuxtRouteRules || {} }),
)
const matcher = exportMatcher(routeRulesMatcher)
const manifestOutputPath = joinURL(
'/',
environmentOptions?.nuxtRuntimeConfig.app?.buildAssetsDir || '_nuxt',
'builds',
)
const manifestBaseRoutePath = joinURL('/_', manifestOutputPath)
h3App.use(
`${manifestBaseRoutePath}/latest.json`,
defineEventHandler(() => ({
id: 'test',
timestamp,
})),
)
h3App.use(
`${manifestBaseRoutePath}/meta/test.json`,
defineEventHandler(() => ({
id: 'test',
timestamp,
matcher,
prerendered: [],
})),
)
h3App.use(
`${manifestBaseRoutePath}/meta/dev.json`,
defineEventHandler(() => ({
id: 'test',
timestamp,
matcher,
prerendered: [],
})),
)
registry.add(`${manifestOutputPath}/latest.json`)
registry.add(`${manifestOutputPath}/meta/test.json`)
registry.add(`${manifestOutputPath}/meta/dev.json`)
return {
// called after all tests with this env have been run
teardown() {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
keys.forEach(key => delete global[key])
originals.forEach((v, k) => (global[k] = v))
teardown()
},
}
},
}