Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: initialize environment only once for no-threads #1263

Merged
merged 1 commit into from May 8, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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
}
}