Skip to content

Commit

Permalink
feat: save vitest state in global variable (#739)
Browse files Browse the repository at this point in the history
  • Loading branch information
poyoho committed Feb 14, 2022
1 parent d4415fe commit 32ad454
Show file tree
Hide file tree
Showing 9 changed files with 32 additions and 32 deletions.
2 changes: 1 addition & 1 deletion packages/vitest/src/integrations/snapshot/client.ts
Expand Up @@ -34,7 +34,7 @@ export class SnapshotClient {
this.testFile = this.test!.file!.filepath
this.snapshotState = new SnapshotState(
resolveSnapshotPath(this.testFile),
process.__vitest_worker__!.config.snapshotOptions,
__vitest_worker__!.config.snapshotOptions,
)
}
}
Expand Down
2 changes: 1 addition & 1 deletion packages/vitest/src/node/mocker.ts
Expand Up @@ -73,7 +73,7 @@ export class VitestMocker {
}

public getSuiteFilepath() {
return process.__vitest_worker__?.filepath || 'global'
return __vitest_worker__?.filepath || 'global'
}

public getMocks() {
Expand Down
4 changes: 2 additions & 2 deletions packages/vitest/src/runtime/context.ts
Expand Up @@ -17,11 +17,11 @@ export async function runWithSuite(suite: SuiteCollector, fn: (() => Awaitable<v
}

export function getDefaultTestTimeout() {
return process.__vitest_worker__!.config!.testTimeout
return __vitest_worker__!.config!.testTimeout
}

export function getDefaultHookTimeout() {
return process.__vitest_worker__!.config!.hookTimeout
return __vitest_worker__!.config!.hookTimeout
}

export function withTimeout<T extends((...args: any[]) => any)>(fn: T, _timeout?: number): T {
Expand Down
4 changes: 2 additions & 2 deletions packages/vitest/src/runtime/entry.ts
Expand Up @@ -14,12 +14,12 @@ export async function run(files: string[], config: ResolvedConfig): Promise<void
if (!['node', 'jsdom', 'happy-dom'].includes(env))
throw new Error(`Unsupported environment: ${env}`)

process.__vitest_worker__.filepath = file
__vitest_worker__.filepath = file

await withEnv(env as BuiltinEnvironment, config.environmentOptions || {}, async() => {
await startTests([file], config)
})

process.__vitest_worker__.filepath = undefined
__vitest_worker__.filepath = undefined
}
}
2 changes: 1 addition & 1 deletion packages/vitest/src/runtime/rpc.ts
@@ -1,3 +1,3 @@
export const rpc = () => {
return process.__vitest_worker__!.rpc
return __vitest_worker__!.rpc
}
6 changes: 3 additions & 3 deletions packages/vitest/src/runtime/run.ts
Expand Up @@ -63,7 +63,7 @@ export async function runTest(test: Test) {

getSnapshotClient().setTest(test)

process.__vitest_worker__.current = test
__vitest_worker__.current = test

try {
await callSuiteHook(test.suite, 'beforeEach', [test, test.suite])
Expand Down Expand Up @@ -114,7 +114,7 @@ export async function runTest(test: Test) {

test.result.duration = performance.now() - start

process.__vitest_worker__.current = undefined
__vitest_worker__.current = undefined

updateTask(test)
}
Expand Down Expand Up @@ -213,7 +213,7 @@ export async function startTests(paths: string[], config: ResolvedConfig) {
}

export function clearModuleMocks() {
const { clearMocks, mockReset, restoreMocks } = process.__vitest_worker__.config
const { clearMocks, mockReset, restoreMocks } = __vitest_worker__.config

// since each function calls another, we can just call one
if (restoreMocks)
Expand Down
6 changes: 3 additions & 3 deletions packages/vitest/src/runtime/setup.ts
Expand Up @@ -26,7 +26,7 @@ export function setupConsoleLogSpy() {
rpc().onUserConsoleLog({
type: 'stdout',
content: String(data),
taskId: process.__vitest_worker__.current?.id,
taskId: __vitest_worker__.current?.id,
time: Date.now(),
})
callback()
Expand All @@ -37,7 +37,7 @@ export function setupConsoleLogSpy() {
rpc().onUserConsoleLog({
type: 'stderr',
content: String(data),
taskId: process.__vitest_worker__.current?.id,
taskId: __vitest_worker__.current?.id,
time: Date.now(),
})
callback()
Expand Down Expand Up @@ -69,7 +69,7 @@ export async function runSetupFiles(config: ResolvedConfig) {
const files = toArray(config.setupFiles)
await Promise.all(
files.map(async(file) => {
process.__vitest_worker__.moduleCache.delete(file)
__vitest_worker__.moduleCache.delete(file)
await import(file)
}),
)
Expand Down
24 changes: 7 additions & 17 deletions packages/vitest/src/runtime/worker.ts
@@ -1,7 +1,6 @@
import { resolve } from 'pathe'
import type { BirpcReturn } from 'birpc'
import { createBirpc } from 'birpc'
import type { ModuleCache, ResolvedConfig, Test, WorkerContext, WorkerRPC } from '../types'
import type { ModuleCache, ResolvedConfig, WorkerContext, WorkerGlobalState, WorkerRPC } from '../types'
import { distDir } from '../constants'
import { executeInViteNode } from '../node/execute'
import { rpc } from './rpc'
Expand All @@ -10,6 +9,7 @@ let _viteNode: {
run: (files: string[], config: ResolvedConfig) => Promise<void>
collect: (files: string[], config: ResolvedConfig) => Promise<void>
}
let __vitest_worker__: WorkerGlobalState
const moduleCache: Map<string, ModuleCache> = new Map()
const mockMap = {}

Expand Down Expand Up @@ -53,14 +53,15 @@ async function startViteNode(ctx: WorkerContext) {
}

function init(ctx: WorkerContext) {
if (process.__vitest_worker__ && ctx.config.threads && ctx.config.isolate)
throw new Error(`worker for ${ctx.files.join(',')} already initialized by ${process.__vitest_worker__.ctx.files.join(',')}. This is probably an internal bug of Vitest.`)
if (__vitest_worker__ && ctx.config.threads && ctx.config.isolate)
throw new Error(`worker for ${ctx.files.join(',')} already initialized by ${__vitest_worker__.ctx.files.join(',')}. This is probably an internal bug of Vitest.`)

process.stdout.write('\0')

const { config, port } = ctx

process.__vitest_worker__ = {
// @ts-expect-error I know what I am doing :P
globalThis.__vitest_worker__ = {
ctx,
moduleCache,
config,
Expand Down Expand Up @@ -92,16 +93,5 @@ export async function run(ctx: WorkerContext) {
}

declare global {
namespace NodeJS {
interface Process {
__vitest_worker__: {
ctx: WorkerContext
config: ResolvedConfig
rpc: BirpcReturn<WorkerRPC>
current?: Test
filepath?: string
moduleCache: Map<string, ModuleCache>
}
}
}
let __vitest_worker__: import('vitest').WorkerGlobalState
}
14 changes: 12 additions & 2 deletions packages/vitest/src/types/worker.ts
@@ -1,7 +1,8 @@
import type { MessagePort } from 'worker_threads'
import type { FetchFunction, RawSourceMap, ViteNodeResolveId } from 'vite-node'
import type { FetchFunction, ModuleCache, RawSourceMap, ViteNodeResolveId } from 'vite-node'
import type { BirpcReturn } from 'birpc'
import type { ResolvedConfig } from './config'
import type { File, TaskResultPack } from './tasks'
import type { File, TaskResultPack, Test } from './tasks'
import type { SnapshotResult } from './snapshot'
import type { UserConsoleLog } from './general'

Expand All @@ -27,3 +28,12 @@ export interface WorkerRPC {

snapshotSaved: (snapshot: SnapshotResult) => void
}

export interface WorkerGlobalState {
ctx: WorkerContext
config: ResolvedConfig
rpc: BirpcReturn<WorkerRPC>
current?: Test
filepath?: string
moduleCache: Map<string, ModuleCache>
}

0 comments on commit 32ad454

Please sign in to comment.