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: new environmentMatchGlobs option to auto infer env based on glob #2714

Merged
merged 4 commits into from Jan 19, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
2 changes: 2 additions & 0 deletions packages/vitest/src/node/config.ts
Expand Up @@ -239,6 +239,8 @@ export function resolveConfig(
...resolved.typecheck,
}

resolved.environmentMatchGlobs = (resolved.environmentMatchGlobs || []).map(i => [resolve(resolved.root, i[0]), i[1]])

if (mode === 'typecheck') {
resolved.include = resolved.typecheck.include
resolved.exclude = resolved.typecheck.exclude
Expand Down
19 changes: 17 additions & 2 deletions packages/vitest/src/runtime/entry.ts
Expand Up @@ -5,6 +5,7 @@ import { vi } from '../integrations/vi'
import { envs } from '../integrations/env'
import { setupGlobalEnv, withEnv } from './setup'
import { startTests } from './run'
import mm from 'micromatch'

function groupBy<T, K extends string | number | symbol >(collection: T[], iteratee: (item: T) => K) {
return collection.reduce((acc, item) => {
Expand All @@ -31,7 +32,21 @@ export async function run(files: string[], config: ResolvedConfig): Promise<void
// 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'

// 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 (let [glob, target] of config.environmentMatchGlobs || []) {
if (mm.isMatch(file, glob)) {
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,
Expand All @@ -52,7 +67,7 @@ export async function run(files: string[], config: ResolvedConfig): Promise<void

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

// @ts-expect-error untyped global
globalThis.__vitest_environment__ = environment

Expand Down
6 changes: 6 additions & 0 deletions packages/vitest/src/runtime/setup.ts
Expand Up @@ -8,6 +8,7 @@ import * as VitestIndex from '../index'
import { resetRunOnceCounter } from '../integrations/run-once'
import { RealDate } from '../integrations/mock/date'
import { rpc } from './rpc'
import { expect } from '../integrations/chai'

let globalSetup = false
export async function setupGlobalEnv(config: ResolvedConfig) {
Expand Down Expand Up @@ -180,6 +181,11 @@ export async function withEnv(
fn: () => Promise<void>,
) {
const config: Environment = (environments as any)[name] || await loadEnvironment(name)
// @ts-expect-error untyped global
globalThis.__vitest_environment__ = config.name || name
expect.setState({
environment: config.name || name || 'node',
})
const env = await config.setup(globalThis, options)
try {
await fn()
Expand Down
16 changes: 16 additions & 0 deletions packages/vitest/src/types/config.ts
Expand Up @@ -138,6 +138,22 @@ export interface InlineConfig {
*/
environmentOptions?: EnvironmentOptions

/**
* Automatically assign environment based on globs. The first match will be used.
*
* Format: [glob, environment-name]
*
* @default []
* @example [
* // all tests in tests/dom will run in jsdom
* ['tests/dom/**', 'jsdom'],
* // all tests in tests/ with .edge.test.ts will run in edge-runtime
* ['**\/*.edge.test.ts', 'edge-runtime'],
* // ...
* ]
*/
environmentMatchGlobs?: [string, BuiltinEnvironment | string][]
antfu marked this conversation as resolved.
Show resolved Hide resolved

/**
* Update snapshot
*
Expand Down
78 changes: 25 additions & 53 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 11 additions & 0 deletions test/env-glob/package.json
@@ -0,0 +1,11 @@
{
"name": "@vitest/test-env-glob",
"private": true,
"scripts": {
"test": "vitest",
"coverage": "vitest run --coverage"
},
"devDependencies": {
"vitest": "workspace:*"
}
}
6 changes: 6 additions & 0 deletions test/env-glob/test/base.dom.test.ts
@@ -0,0 +1,6 @@
import { expect, test } from 'vitest'

test('glob on extension', () => {
expect(typeof window).not.toBe('undefined')
expect(expect.getState().environment).toBe('happy-dom')
})
6 changes: 6 additions & 0 deletions test/env-glob/test/base.test.ts
@@ -0,0 +1,6 @@
import { expect, test } from 'vitest'

test('default', () => {
expect(typeof window).toBe('undefined')
expect(expect.getState().environment).toBe('node')
})
6 changes: 6 additions & 0 deletions test/env-glob/test/dom/base.spec.ts
@@ -0,0 +1,6 @@
import { expect, test } from 'vitest'

test('glob on folder', () => {
expect(typeof window).not.toBe('undefined')
expect(expect.getState().environment).toBe('jsdom')
})
9 changes: 9 additions & 0 deletions test/env-glob/test/dom/overrides.spec.ts
@@ -0,0 +1,9 @@
import { expect, test } from 'vitest'

/**
* @vitest-environment edge-runtime
*/

test('glob on folder overrides', () => {
expect(expect.getState().environment).toBe('edge-runtime')
})
10 changes: 10 additions & 0 deletions test/env-glob/vitest.config.ts
@@ -0,0 +1,10 @@
import { defineConfig } from 'vitest/config'

export default defineConfig({
test: {
environmentMatchGlobs: [
['**/*.dom.test.ts', 'happy-dom'],
['test/dom/**', 'jsdom']
]
},
})