Skip to content

Commit

Permalink
feat: initialize environment only once for no-threads (#1263)
Browse files Browse the repository at this point in the history
  • Loading branch information
sheremet-va committed May 8, 2022
1 parent 5750cf0 commit 2d3f8d5
Showing 1 changed file with 36 additions and 14 deletions.
50 changes: 36 additions & 14 deletions packages/vitest/src/runtime/entry.ts
Expand Up @@ -9,23 +9,45 @@ export async function run(files: string[], config: ResolvedConfig): Promise<void

const workerState = getWorkerState()

for (const file of files) {
workerState.mockMap.clear()
resetModules()
const envs = ['node', 'jsdom', 'happy-dom']

// if calling from a worker, there will always be one file
// if calling with no-threads, this will be the whole suite
const filesWithEnv = await Promise.all(files.map(async (file) => {
const code = await fs.readFile(file, 'utf-8')

const env = code.match(/@(?:vitest|jest)-environment\s+?([\w-]+)\b/)?.[1] || config.environment || 'node'

if (!['node', 'jsdom', 'happy-dom'].includes(env))
throw new Error(`Unsupported environment: ${env}`)

workerState.filepath = file

await withEnv(env as BuiltinEnvironment, config.environmentOptions || {}, async () => {
await startTests([file], config)
if (!envs.includes(env))
throw new Error(`Unsupported environment: "${env}" in ${file}`)
return {
file,
env: env as BuiltinEnvironment,
}
}))

const filesByEnv = filesWithEnv.reduce((acc, { file, env }) => {
acc[env] ||= []
acc[env].push(file)
return acc
}, {} as Record<BuiltinEnvironment, string[]>)

for (const env of envs) {
const environment = env as BuiltinEnvironment
const files = filesByEnv[environment]

if (!files || !files.length)
continue

await withEnv(environment, config.environmentOptions || {}, async () => {
for (const file of files) {
workerState.mockMap.clear()
resetModules()

workerState.filepath = file

await startTests([file], config)

workerState.filepath = undefined
}
})

workerState.filepath = undefined
}
}

0 comments on commit 2d3f8d5

Please sign in to comment.