diff --git a/packages/vitest/src/runtime/entry.ts b/packages/vitest/src/runtime/entry.ts index 2f837a58c66e..eb8112ade641 100644 --- a/packages/vitest/src/runtime/entry.ts +++ b/packages/vitest/src/runtime/entry.ts @@ -9,23 +9,45 @@ export async function run(files: string[], config: ResolvedConfig): Promise { 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) + + 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 } }