/
execute.ts
48 lines (36 loc) · 1.32 KB
/
execute.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
import { ViteNodeRunner } from 'vite-node/client'
import type { ModuleCache, ViteNodeRunnerOptions } from 'vite-node'
import type { SuiteMocks } from './mocker'
import { VitestMocker } from './mocker'
export interface ExecuteOptions extends ViteNodeRunnerOptions {
files: string[]
mockMap: SuiteMocks
}
export async function executeInViteNode(options: ExecuteOptions) {
const runner = new VitestRunner(options)
// provide the vite define variable in this context
await runner.executeId('/@vite/env')
const result: any[] = []
for (const file of options.files)
result.push(await runner.executeFile(file))
return result
}
export class VitestRunner extends ViteNodeRunner {
mocker: VitestMocker
constructor(public options: ExecuteOptions) {
super(options)
this.mocker = new VitestMocker(options, this.moduleCache)
}
prepareContext(context: Record<string, any>) {
const request = context.__vite_ssr_import__
const mocker = this.mocker.withRequest(request)
mocker.on('mocked', (dep: string, module: Partial<ModuleCache>) => {
this.setCache(dep, module)
})
return Object.assign(context, {
__vite_ssr_import__: (dep: string) => mocker.requestWithMock(dep),
__vite_ssr_dynamic_import__: (dep: string) => mocker.requestWithMock(dep),
__vitest_mocker__: mocker,
})
}
}