-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
test-helpers.ts
48 lines (42 loc) · 1.36 KB
/
test-helpers.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 { promises as fs } from 'node:fs'
import mm from 'micromatch'
import type { EnvironmentOptions, ResolvedConfig, VitestEnvironment } from '../types'
import { groupBy } from './base'
export const envsOrder = [
'node',
'jsdom',
'happy-dom',
'edge-runtime',
]
export interface FileByEnv {
file: string
env: VitestEnvironment
envOptions: EnvironmentOptions | null
}
export async function groupFilesByEnv(files: string[], config: ResolvedConfig) {
const filesWithEnv = await Promise.all(files.map(async (file) => {
const code = await fs.readFile(file, 'utf-8')
// 1. Check for control comments in the file
let env = code.match(/@(?:vitest|jest)-environment\s+?([\w-]+)\b/)?.[1]
// 2. Check for globals
if (!env) {
for (const [glob, target] of config.environmentMatchGlobs || []) {
if (mm.isMatch(file, glob, { cwd: config.root })) {
env = target
break
}
}
}
// 3. Fallback to global env
env ||= config.environment || 'node'
const envOptions = JSON.parse(code.match(/@(?:vitest|jest)-environment-options\s+?(.+)/)?.[1] || 'null')
return {
file,
environment: {
name: env as VitestEnvironment,
options: envOptions ? { [env]: envOptions } as EnvironmentOptions : null,
},
}
}))
return groupBy(filesWithEnv, ({ environment }) => environment.name)
}