@eggjs/tegg-vitest
v3.79.2
Published
Vitest adapter for tegg context injection
Readme
@eggjs/tegg-vitest
Vitest adapter that provides tegg context injection and lifecycle handling via a custom Vitest runner.
Install
This package lives in the tegg monorepo workspace.
Usage
- Create a Vitest setup file that calls
configureTeggRunner:
// vitest.setup.ts
import path from 'path';
import mm from 'egg-mock';
import { configureTeggRunner } from '@eggjs/tegg-vitest';
const app = mm.app({
baseDir: path.join(__dirname, 'fixtures/apps/my-app'),
framework: require.resolve('egg'),
});
configureTeggRunner({
getApp: () => app,
restoreMocks: true,
parallel: process.env.VITEST_WORKER_ID != null,
});- Wire it in
vitest.config.tswith the custom runner:
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
environment: 'node',
setupFiles: ['./vitest.setup.ts'],
runner: '@eggjs/tegg-vitest/runner',
},
});Options
getApp: Provide a custom app getter. Default:require('egg-mock/bootstrap').app.parallel: Skip autoapp.close()when running in parallel mode. Default: auto-detected fromVITEST_WORKER_ID.restoreMocks: Restore mocks after each test (defaults to true).
Lifecycle & Context Injection
The custom runner extends Vitest's VitestTestRunner and manages tegg context at the runner level:
importFile(collection phase): Captures per-file config fromconfigureTeggRunner()and callsapp.ready().onBeforeRunSuite(file suite): Creates a suite-scopedctxviaapp.mockContext(), overridesctxStorage.getStore(), and opens a heldbeginModuleScopethat stays alive for the entire file.onBeforeRunTask(per test): Creates a per-testctxand opens a heldbeginModuleScopefor the test.onAfterRunTask: Releases the test scope, restores mocks, and restoresctxStorage.getStore()back to the suitectx.onAfterRunSuite: Releases the suite scope, restores originalgetStore(), and callsapp.close()unlessparallelis true.
Limitations
- Context is managed at the file suite level.
egg-mock's Mocha runner patch can switch context at thedescribesuite level. If your tests rely on describe-scoped suite context, you must manage that manually. - If
getAppthrows or returnsundefined, the adapter will run tests without context injection.
