### Example setup file content Source: https://vitest.dev/guide/learn/setup-teardown Provides an example of what a setup file might contain, such as extending Vitest's expect API. ```javascript // This runs before every test file import { expect } from 'vitest' import { customMatchers } from './custom-matchers.js' expect.extend(customMatchers) ``` -------------------------------- ### Vitest output after running tests Source: https://vitest.dev/guide Example output shown by Vitest after successfully running the tests. ```txt ✓ sum.test.js (1) ✓ adds 1 + 2 to equal 3 Test Files 1 passed (1) Tests 1 passed (1) Start at 02:15:44 Duration 311ms ``` -------------------------------- ### Example of a setup file with global variable management Source: https://vitest.dev/config/setupfiles This example demonstrates how to use a setup file to initialize global configurations and manage state across test runs, preventing redundant heavy computations. ```typescript import { config } from '@some-testing-lib' if (!globalThis.setupInitialized) { config.plugins = [myCoolPlugin] computeHeavyThing() globalThis.setupInitialized = true } // hooks reset before each test file afterEach(() => { cleanup() }) globalThis.resetBeforeEachTest = true ``` -------------------------------- ### Install Vitest with different package managers Source: https://vitest.dev/guide Commands to install Vitest as a development dependency using npm, yarn, pnpm, and bun. ```bash npm install -D vitest ``` ```bash yarn add -D vitest ``` ```bash pnpm add -D vitest ``` ```bash bun add -D vitest ``` -------------------------------- ### Setup File Example Source: https://vitest.dev/guide/lifecycle Example of a setup file that runs before each test file, allowing for initialization of global state and registration of hooks. ```typescript import { afterEach } from 'vitest' // Runs before each test file console.log('Setup file executing') // Register hooks that apply to all tests afterEach(() => { cleanup() }) ``` -------------------------------- ### Global Setup Provide Example Source: https://vitest.dev/api/advanced/test-project Shows how to use the `provide` function in a global setup file. ```javascript export default function setup ({ provide }) { provide('wsPort', 3000) } ``` -------------------------------- ### Global Setup Example Source: https://vitest.dev/guide/lifecycle Example of a global setup file that runs once before all tests, providing data to tests and performing cleanup. ```typescript export function setup(project) { // Runs once before all tests console.log('Global setup') // Share data with tests project.provide('apiUrl', 'http://localhost:3000') } export function teardown() { // Runs once after all tests console.log('Global teardown') } ``` -------------------------------- ### Execution Order Example Source: https://vitest.dev/guide/learn/setup-teardown Provides an example demonstrating the execution order of nested hooks (`beforeAll`, `afterAll`, `beforeEach`, `afterEach`) within `describe` blocks and at the top level. ```javascript import { afterAll, afterEach, beforeAll, beforeEach, describe, test } from 'vitest' beforeAll(() => console.log('1 - beforeAll')) afterAll(() => console.log('8 - afterAll')) beforeEach(() => console.log('2 - beforeEach')) afterEach(() => console.log('5 - afterEach')) describe('suite', () => { beforeEach(() => console.log('3 - inner beforeEach')) afterEach(() => console.log('4 - inner afterEach')) test('first test', () => { console.log(' first test') }) test('second test', () => { console.log(' second test') }) }) ``` -------------------------------- ### example.test.ts Source: https://vitest.dev/config/globalsetup Example of injecting data provided by global setup into tests. ```ts import { inject } from 'vitest' inject('wsPort') === 3000 ``` -------------------------------- ### Repeating Setup for Each Test Source: https://vitest.dev/guide/learn/setup-teardown Demonstrates the use of `beforeEach` and `afterEach` hooks to ensure each test starts with a known state and that mutations do not leak between tests. ```javascript import { afterEach, beforeEach, expect, test } from 'vitest' let items beforeEach(() => { items = ['apple', 'banana', 'cherry'] }) afterEach(() => { items = [] }) test('items starts with 3 fruits', () => { expect(items).toHaveLength(3) }) test('can add an item', () => { items.push('date') expect(items).toHaveLength(4) // afterEach will reset items for the next test, // so this mutation won't leak into other tests }) ``` -------------------------------- ### Install Vitest UI Source: https://vitest.dev/guide/ui Install the Vitest UI package as a dev dependency. ```bash npm i -D @vitest/ui ``` -------------------------------- ### Start Vitest with UI Source: https://vitest.dev/guide/ui Start Vitest tests with the UI enabled by passing the --ui flag. ```bash vitest --ui ``` -------------------------------- ### Example test for the sum function Source: https://vitest.dev/guide A Vitest test file that imports and tests the sum function. ```js import { expect, test } from 'vitest' import { sum } from './sum.js' test('adds 1 + 2 to equal 3', () => { expect(sum(1, 2)).toBe(3) }) ``` -------------------------------- ### Example sum function Source: https://vitest.dev/guide A simple JavaScript function that adds two numbers. ```js export function sum(a, b) { return a + b } ``` -------------------------------- ### globalSetup.ts Source: https://vitest.dev/config/globalsetup Example of providing serializable data to tests via global setup. ```ts import type { TestProject } from 'vitest/node' export default function setup(project: TestProject) { project.provide('wsPort', 3000) } declare module 'vitest' { export interface ProvidedContext { wsPort: number } } ``` -------------------------------- ### One-Time Setup Source: https://vitest.dev/guide/learn/setup-teardown Illustrates the use of `beforeAll` and `afterAll` hooks for expensive setup operations that should only run once per file, such as database connections. ```javascript import { afterAll, beforeAll, expect, test } from 'vitest' let db beforeAll(async () => { db = await connectToDatabase() }) afterAll(async () => { await db.close() }) test('can query users', async () => { const users = await db.query('SELECT * FROM users') expect(users.length).toBeGreaterThan(0) }) test('can query products', async () => { const products = await db.query('SELECT * FROM products') expect(products.length).toBeGreaterThan(0) }) ``` -------------------------------- ### GraphQL Setup Source: https://vitest.dev/guide/mocking/requests Example of setting up Mock Service Worker (MSW) for mocking GraphQL requests in Vitest. ```javascript import { afterAll, afterEach, beforeAll } from 'vitest' import { setupServer } from 'msw/node' import { graphql, HttpResponse } from 'msw' const posts = [ { userId: 1, id: 1, title: 'first post title', body: 'first post body', }, // ... ] const graphqlHandlers = [ graphql.query('ListPosts', () => { return HttpResponse.json({ data: { posts }, }) }), ] const server = setupServer(...graphqlHandlers) // Start server before all tests beforeAll(() => server.listen({ onUnhandledRequest: 'error' })) // Close server after all tests afterAll(() => server.close()) // Reset handlers after each test for test isolation afterEach(() => server.resetHandlers()) ``` -------------------------------- ### Configuring setup files Source: https://vitest.dev/guide/learn/setup-teardown Shows how to configure Vitest to use setup files for code that should run before every test file in the project. ```javascript import { defineConfig } from 'vitest/config' export default defineConfig({ test: { setupFiles: ['./test/setup.js'], }, }) ``` -------------------------------- ### Filtering with --project flag Source: https://vitest.dev/guide/browser/multiple-setups Example of filtering browser instances using the `--project` flag in the command line. ```shell $ vitest --project=chromium ``` -------------------------------- ### Example Source: https://vitest.dev/config/include An example of how to configure the include option in Vitest. ```javascript import { defineConfig } from 'vitest/config' export default defineConfig({ test: { include: [ './test', './**/*.{test,spec}.tsx?', ], }, }) ``` -------------------------------- ### HTTP Setup Source: https://vitest.dev/guide/mocking/requests Example of setting up Mock Service Worker (MSW) for mocking HTTP requests in Vitest. ```javascript import { afterAll, afterEach, beforeAll } from 'vitest' import { setupServer } from 'msw/node' import { http, HttpResponse } from 'msw' const posts = [ { userId: 1, id: 1, title: 'first post title', body: 'first post body', }, // ... ] export const restHandlers = [ http.get('https://rest-endpoint.example/path/to/posts', () => { return HttpResponse.json(posts) }), ] const server = setupServer(...restHandlers) // Start server before all tests beforeAll(() => server.listen({ onUnhandledRequest: 'error' })) // Close server after all tests afterAll(() => server.close()) // Reset handlers after each test for test isolation afterEach(() => server.resetHandlers()) ``` -------------------------------- ### Different Setups Source: https://vitest.dev/guide/browser/multiple-setups Specifying different browser setups with independent config options, including `setupFiles` and `provide` for custom values. ```typescript import { defineConfig } from 'vitest/config' import { playwright } from '@vitest/browser-playwright' export default defineConfig({ test: { browser: { enabled: true, provider: playwright(), headless: true, instances: [ { browser: 'chromium', name: 'chromium-1', setupFiles: ['./ratio-setup.ts'], provide: { ratio: 1, }, }, { browser: 'chromium', name: 'chromium-2', provide: { ratio: 2, }, }, ], }, }, }) ``` ```typescript import { expect, inject, test } from 'vitest' import { globalSetupModifier } from './example.js' test('ratio works', () => { expect(inject('ratio') * globalSetupModifier).toBe(14) }) ``` -------------------------------- ### WebSocket Setup Source: https://vitest.dev/guide/mocking/requests Example of setting up Mock Service Worker (MSW) for mocking WebSocket requests in Vitest. ```javascript import { afterAll, afterEach, beforeAll } from 'vitest' import { setupServer } from 'msw/node' import { ws } from 'msw' const chat = ws.link('wss://chat.example.com') const wsHandlers = [ chat.addEventListener('connection', ({ client }) => { client.addEventListener('message', (event) => { console.log('Received message from client:', event.data) // Echo the received message back to the client client.send(`Server received: ${event.data}`) }) }), ] const server = setupServer(...wsHandlers) // Start server before all tests beforeAll(() => server.listen({ onUnhandledRequest: 'error' })) // Close server after all tests afterAll(() => server.close()) // Reset handlers after each test for test isolation afterEach(() => server.resetHandlers()) ``` -------------------------------- ### Utility Import Update Source: https://vitest.dev/guide/migration Example demonstrating the update for importing utility functions from `@vitest/browser/utils` to `vitest/browser`. ```ts import { getElementError } from '@vitest/browser/utils' // [!code --] import { utils } from 'vitest/browser' // [!code ++] const { getElementError } = utils // [!code ++] ``` -------------------------------- ### exports Source: https://vitest.dev/config/globalsetup Global setup file can export named functions setup and teardown. ```js export function setup(project) { console.log('setup') } export function teardown() { console.log('teardown') } ``` -------------------------------- ### `spyOn` and `fn` Support Constructors Source: https://vitest.dev/guide/migration Example demonstrating how to spy on a constructor with `vi.spyOn` and mock its implementation using function or class keywords. ```typescript const cart = { Apples: class Apples { getApples() { return 42 } } } const Spy = vi.spyOn(cart, 'Apples') .mockImplementation(() => ({ getApples: () => 0 })) // [!code --] // with a function keyword .mockImplementation(function () { this.getApples = () => 0 }) // with a custom class .mockImplementation(class MockApples { getApples() { return 0 } }) const mock = new Spy() ``` -------------------------------- ### Multiple Browser Instances Configuration Source: https://vitest.dev/config/browser/instances Example of configuring multiple browser instances, demonstrating inheritance of root config options and specifying browser-specific setup files. ```typescript export default defineConfig({ test: { setupFile: ['./root-setup-file.js'], browser: { enabled: true, testerHtmlPath: './custom-path.html', instances: [ { // will have both setup files: "root" and "browser" setupFile: ['./browser-setup-file.js'], // implicitly has "testerHtmlPath" from the root config // [!code warning] // testerHtmlPath: './custom-path.html', // [!code warning] }, ], }, }, }) ``` -------------------------------- ### vitest.config.js and vitest.workspace.js migration Source: https://vitest.dev/guide/migration Example showing the migration from the `workspace` configuration option to the `projects` option in `vitest.config.js`, and the removal of `vitest.workspace.js`. ```ts import { defineConfig } from 'vitest/config' export default defineConfig({ test: { workspace: './vitest.workspace.js', // [!code --] projects: [ // [!code ++] './packages/*', // [!code ++] { test: { // [!code ++] name: 'unit', // [!code ++] }, }, // [!code ++] ] } }) ``` ```ts import { defineWorkspace } from 'vitest/config' // [!code --] export default defineWorkspace([ './packages/*', { test: { name: 'unit', }, }, ]) ``` -------------------------------- ### createVitest API Source: https://vitest.dev/guide/advanced The createVitest function returns the same Vitest instance as startVitest, but it doesn't start tests and doesn't validate installed packages. ```typescript function createVitest( mode: VitestRunMode, options: CliOptions, viteOverrides: ViteUserConfig = {}, vitestOptions: VitestOptions = {}, ): Promise ``` ```javascript import { createVitest } from 'vitest/node' const vitest = await createVitest('test', { watch: false, }) ``` -------------------------------- ### Custom Environment Implementation Source: https://vitest.dev/guide/environment An example of creating a custom Vitest environment package. It shows the structure of the exported environment object, including optional `setupVM` and `setup` methods. ```typescript import type { Environment } from 'vitest/runtime' export default { name: 'custom', viteEnvironment: 'ssr', // optional - only if you support "vmForks" or "vmThreads" pools async setupVM() { const vm = await import('node:vm') const context = vm.createContext() return { getVmContext() { return context }, teardown() { // called after all tests with this env have been run } } }, setup() { // custom setup return { teardown() { // called after all tests with this env have been run } } } } ``` -------------------------------- ### Initializing browser configuration Source: https://vitest.dev/guide/cli Example command to set up Vitest for browser testing. ```bash vitest init browser ``` -------------------------------- ### Example for test projects Source: https://vitest.dev/config/include An example of defining include for test projects. ```javascript import { defineConfig } from 'vitest/config' export default defineConfig({ test: { projects: [ { test: { name: 'unit', include: ['./test/unit/*.test.js'], }, }, { test: { name: 'e2e', include: ['./test/e2e/*.test.js'], }, }, ], }, }) ``` -------------------------------- ### unmount example Source: https://vitest.dev/api/browser/react Example demonstrating how to unmount a rendered component and check its state. ```jsx import { render } from 'vitest-browser-react' const { container, unmount } = await render() await unmount() // your component has been unmounted and now: container.innerHTML === '' ``` -------------------------------- ### Restoring Spies Source: https://vitest.dev/guide/migration Example of restoring spies. ```typescript // Sinon spy.restore() sinon.restore() // restore all // Vitest spy.mockRestore() vi.restoreAllMocks() // restore all ``` -------------------------------- ### Defining reusable fixtures with test.extend Source: https://vitest.dev/guide/learn/setup-teardown Illustrates how to define reusable fixtures using `test.extend` for automatic setup and cleanup, improving test organization and type safety. ```javascript import { test as baseTest } from 'vitest' export const test = baseTest .extend('db', async ({}, { onCleanup }) => { const db = await createDatabase() onCleanup(() => db.close()) return db }) .extend('user', async ({ db }) => { return await db.createUser({ name: 'Alice' }) }) ``` -------------------------------- ### Standalone Mode with Filename Filter - CLI Example Source: https://vitest.dev/guide/migration Example of using the `--standalone` flag with a filename filter in the Vitest CLI. ```bash # In Vitest v3 and below this command would ignore "math.test.ts" filename filter. # In Vitest v4 the math.test.ts will run automatically. $ vitest --standalone math.test.ts ``` -------------------------------- ### Stubbing Implementations Source: https://vitest.dev/guide/migration Example of stubbing implementations for spies/stubs. ```typescript // Sinon stub.callsFake(arg => arg * 2) // Vitest stub.mockImplementation(arg => arg * 2) ``` -------------------------------- ### Playwright Browser Installation in CI Source: https://vitest.dev/guide/browser/visual-regression-testing Example of a GitHub Actions workflow step to install Playwright browsers for visual regression testing. ```yaml # ...the rest of the workflow - name: Install Playwright Browsers run: npx --no playwright install --with-deps --only-shell ``` -------------------------------- ### Scoping with `describe` Source: https://vitest.dev/guide/learn/setup-teardown Shows how `describe` blocks can scope hooks, allowing different setup and teardown logic for different groups of tests within the same file. ```javascript import { beforeEach, describe, expect, test } from 'vitest' describe('math operations', () => { let value beforeEach(() => { value = 0 }) test('can add', () => { value += 5 expect(value).toBe(5) }) test('can subtract', () => { value -= 3 expect(value).toBe(-3) // value was reset to 0 by beforeEach }) }) describe('string operations', () => { let text beforeEach(() => { text = 'hello' }) test('can uppercase', () => { expect(text.toUpperCase()).toBe('HELLO') }) }) ``` -------------------------------- ### startVitest example Source: https://vitest.dev/guide/advanced/tests Initiates Vitest, validates packages, and runs tests immediately. ```typescript import { startVitest } from 'vitest/node' const vitest = await startVitest( 'test', [], // CLI filters {}, {}, {}, ) const testModules = vitest.state.getTestModules() for (const testModule of testModules) { console.log(testModule.moduleId, testModule.ok() ? 'passed' : 'failed') } ``` -------------------------------- ### OpenTelemetry SDK Example Source: https://vitest.dev/config/experimental Example of how to set up an OpenTelemetry SDK in a separate file and configure Vitest to use it. ```js import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node' import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto' import { NodeSDK } from '@opentelemetry/sdk-node' const sdk = new NodeSDK({ serviceName: 'vitest', traceExporter: new OTLPTraceExporter(), instrumentations: [getNodeAutoInstrumentations()], }) sdk.start() export default sdk ``` ```js import { defineConfig } from 'vitest/config' export default defineConfig({ test: { experimental: { openTelemetry: { enabled: true, sdkPath: './otel.js', }, }, }, }) ``` -------------------------------- ### Timers Source: https://vitest.dev/guide/migration Example of using fake timers, common to both Sinon and Vitest. ```typescript // Sinon const clock = sinon.useFakeTimers() clock.tick(1000) clock.restore() // Vitest import { vi } from 'vitest' vi.useFakeTimers() vi.advanceTimersByTime(1000) vi.useRealTimers() ``` -------------------------------- ### Stubbing Return Values Source: https://vitest.dev/guide/migration Example of stubbing return values for spies/stubs. ```typescript // Sinon stub.returns(42) stub.onFirstCall().returns(1) stub.onSecondCall().returns(2) // Vitest stub.mockReturnValue(42) stub.mockReturnValueOnce(1) stub.mockReturnValueOnce(2) ``` -------------------------------- ### Hooks Source: https://vitest.dev/guide/migration Example of rewriting a beforeEach hook to use a block body. ```typescript beforeEach(() => setActivePinia(createTestingPinia())) // [!code --] beforeEach(() => { setActivePinia(createTestingPinia()) }) // [!code ++] ``` -------------------------------- ### Manual Installation - Preview Provider Source: https://vitest.dev/guide/browser Install packages manually for the preview provider. ```bash npm install -D vitest @vitest/browser-preview ``` ```bash yarn add -D vitest @vitest/browser-preview ``` ```bash pnpm add -D vitest @vitest/browser-preview ``` ```bash bun add -D vitest @vitest/browser-preview ``` -------------------------------- ### Using fixtures in a test file Source: https://vitest.dev/guide/learn/setup-teardown Demonstrates how to import and use the extended test fixtures in a test file. ```javascript import { expect } from 'vitest' import { test } from './my-test.js' test('user is created', ({ db, user }) => { expect(user.name).toBe('Alice') }) ``` -------------------------------- ### Timeout Source: https://vitest.dev/guide/migration Example of migrating from Jest's 'jest.setTimeout' to Vitest's 'vi.setConfig'. ```typescript jest.setTimeout(5_000) // [!code --] vi.setConfig({ testTimeout: 5_000 }) // [!code ++] ``` -------------------------------- ### Module Mocks Source: https://vitest.dev/guide/migration Example demonstrating the difference in mocking modules between Jest and Vitest. ```typescript jest.mock('./some-path', () => 'hello') // [!code --] vi.mock('./some-path', () => ({ default: 'hello', })) // [!code ++] ``` -------------------------------- ### onTestRunStart Example Source: https://vitest.dev/api/advanced/reporters An example demonstrating how to use the onTestRunStart method to log the number of test files that will run. ```typescript import type { Reporter, TestSpecification } from 'vitest/node' class MyReporter implements Reporter { onTestRunStart(specifications: TestSpecification[]) { console.log(specifications.length, 'test files will run') } } export default new MyReporter() ``` -------------------------------- ### startVitest API Source: https://vitest.dev/guide/advanced The startVitest function returns a Vitest instance if tests can be started. ```typescript function startVitest( mode: VitestRunMode, cliFilters: string[] = [], options: CliOptions = {}, viteOverrides?: ViteUserConfig, vitestOptions?: VitestOptions, ): Promise ``` ```javascript import { startVitest } from 'vitest/node' const vitest = await startVitest('test') await vitest.close() ``` ```typescript import type { TestModule } from 'vitest/node' const vitest = await startVitest('test') console.log(vitest.state.getTestModules()) // [TestModule] ``` -------------------------------- ### setup.node.js Source: https://vitest.dev/guide/features In Node.js, you can manually handle unhandled rejections and uncaught exceptions. ```ts // in Node.js process.on('unhandledRejection', () => { // your own handler }) process.on('uncaughtException', () => { // your own handler }) ``` -------------------------------- ### Done Callback Source: https://vitest.dev/guide/migration Example of rewriting a test that uses the 'done' callback to use Promises. ```javascript it('should work', (done) => { // [!code --] it('should work', () => new Promise(done => { // [!code ++] // ... done() }) // [!code --] })) // [!code ++] ``` -------------------------------- ### Shard Example Source: https://vitest.dev/guide/cli Demonstrates how to split a test suite into multiple parts using the --shard option. ```bash vitest run --shard=1/3 vitest run --shard=2/3 vitest run --shard=3/3 ``` -------------------------------- ### onInit Example Source: https://vitest.dev/api/advanced/reporters An example demonstrating how to use the onInit method to access the Vitest instance and its configuration. ```typescript import type { Reporter, TestSpecification, Vitest } from 'vitest/node' class MyReporter implements Reporter { private vitest!: Vitest onInit(vitest: Vitest) { this.vitest = vitest } onTestRunStart(specifications: TestSpecification[]) { console.log( specifications.length, 'test files will run in', this.vitest.config.root, ) } } export default new MyReporter() ``` -------------------------------- ### Project Naming with browser instances Source: https://vitest.dev/guide/browser/multiple-setups Demonstrates how Vitest assigns project names when using `browser.instances`, including default and custom naming scenarios. ```typescript export default defineConfig({ test: { browser: { instances: [ // name: chromium { browser: 'chromium' }, // name: custom { browser: 'firefox', name: 'custom' }, ] } } }) ``` ```typescript export default defineConfig({ test: { name: 'custom', browser: { instances: [ // name: custom (chromium) { browser: 'chromium' }, // name: manual { browser: 'firefox', name: 'manual' }, ] } } }) ``` -------------------------------- ### Type-Inference in `test.extend` - Fixture with Setup/Cleanup Source: https://vitest.dev/blog/vitest-4-1 Example of a fixture with setup and cleanup logic using `test.extend` and `onCleanup`. ```typescript import { test as baseTest } from 'vitest' export const test = baseTest .extend('tempFile', async ({}, { onCleanup }) => { const filePath = `/tmp/test-${Date.now()}.txt` await fs.writeFile(filePath, 'test data') // Register cleanup - runs after test completes onCleanup(() => fs.unlink(filePath)) return filePath }) ``` -------------------------------- ### Custom Reporter via vitest.config.ts Source: https://vitest.dev/guide/reporters Example of configuring a custom reporter installed from NPM in the vitest.config.ts file. ```typescript export default defineConfig({ test: { reporters: ['some-published-vitest-reporter'] } }) ``` -------------------------------- ### hello-world.test.js Source: https://vitest.dev/guide/mocking/file-system Vitest test for the readHelloWorld function using memfs. ```ts import { beforeEach, expect, it, vi } from 'vitest' import { fs, vol } from 'memfs' import { readHelloWorld } from './read-hello-world.js' // tell vitest to use fs mock from __mocks__ folder // this can be done in a setup file if fs should always be mocked vi.mock('node:fs') vi.mock('node:fs/promises') beforeEach(() => { // reset the state of in-memory fs vol.reset() }) it('should return correct text', () => { const path = '/hello-world.txt' fs.writeFileSync(path, 'hello world') const text = readHelloWorld(path) expect(text).toBe('hello world') }) it('can return a value multiple times', () => { // you can use vol.fromJSON to define several files vol.fromJSON( { './dir1/hw.txt': 'hello dir1', './dir2/hw.txt': 'hello dir2', }, // default cwd '/tmp', ) expect(readHelloWorld('/tmp/dir1/hw.txt')).toBe('hello dir1') expect(readHelloWorld('/tmp/dir2/hw.txt')).toBe('hello dir2') }) ``` -------------------------------- ### Custom Reporter via CLI Source: https://vitest.dev/guide/reporters Example of using a custom reporter installed from NPM via the CLI. ```bash npx vitest --reporter=some-published-vitest-reporter ``` -------------------------------- ### Context Import Update Source: https://vitest.dev/guide/migration Example showing the change in importing the `page` object from `@vitest/browser/context` to `vitest/browser`. ```ts import { page } from '@vitest/browser/context' // [!code --] import { page } from 'vitest/browser' // [!code ++] test('example', async () => { await page.getByRole('button').click() }) ``` -------------------------------- ### Benchmark Output JSON Example Source: https://vitest.dev/config/benchmark Example of how to save benchmark results to a JSON file and use it for comparison. ```bash # save main branch's result git checkout main vitest bench --outputJson main.json # change a branch and compare against main git checkout feature vitest bench --compare main.json ``` -------------------------------- ### Running multiple specific lines Source: https://vitest.dev/guide/cli Example showing how to run tests on multiple specific lines within a file. ```bash $ vitest basic/foo.test.ts:10, basic/foo.test.ts:25 # ✅ ``` -------------------------------- ### Custom Snapshot Matchers Source: https://vitest.dev/guide/migration Example of migrating custom snapshot matchers from 'jest-snapshot' to Vitest's 'Snapshots'. ```typescript const { toMatchSnapshot } = require('jest-snapshot') // [!code --] import { Snapshots } from 'vitest' // [!code ++] const { toMatchSnapshot } = Snapshots // [!code ++] expect.extend({ toMatchTrimmedSnapshot(received: string, length: number) { return toMatchSnapshot.call(this, received.slice(0, length)) }, }) ``` -------------------------------- ### Types Source: https://vitest.dev/guide/migration Example of migrating from Jest's 'jest' namespace for types to Vitest's direct import. ```typescript let fn: jest.Mock<(name: string) => number> // [!code --] import type { Mock } from 'vitest' // [!code ++] let fn: Mock<(name: string) => number> // [!code ++] ``` -------------------------------- ### Cleanup with onTestFinished Source: https://vitest.dev/guide/learn/setup-teardown Demonstrates how to use `onTestFinished` to register a cleanup function immediately after resource creation within a test. ```javascript import { expect, onTestFinished, test } from 'vitest' test('creates a temporary file', () => { const file = createTempFile() onTestFinished(() => { deleteTempFile(file) }) expect(file.exists()).toBe(true) }) ``` -------------------------------- ### Isolation per project Source: https://vitest.dev/guide/migration Example of configuring test isolation on a per-project basis using Vitest Projects. ```typescript import { defineConfig } from 'vitest/config' export default defineConfig({ test: { projects: [ { // Non-isolated unit tests name: 'Unit tests', isolate: false, exclude: ['**.integration.test.ts'], }, { // Isolated integration tests name: 'Integration tests', include: ['**.integration.test.ts'], }, ], }, }) ``` -------------------------------- ### vitest.config.js example for non-Vite projects Source: https://vitest.dev/config This example shows how to configure Vitest using `defineConfig` from 'vitest/config' when not using Vite. ```js import { defineConfig } from 'vitest/config' export default defineConfig({ test: { // ... Specify options here. }, }) ``` -------------------------------- ### Object Syntax (Playwright-Compatible) Source: https://vitest.dev/guide/test-context Example of defining fixtures using Playwright-compatible object syntax, including setup and cleanup. ```typescript import { test as baseTest } from 'vitest' export const test = baseTest.extend({ page: async ({}, use) => { // setup the fixture before each test function const page = await browser.newPage() // use the fixture value await use(page) // cleanup the fixture after each test function await page.close() }, baseUrl: 'http://localhost:3000' }) ``` -------------------------------- ### Running tests with different package managers Source: https://vitest.dev/guide/projects Examples of running Vitest tests using npm, yarn, pnpm, and bun. ```bash npm run test ``` ```bash yarn test ``` ```bash pnpm run test ``` ```bash bun run test ``` -------------------------------- ### Custom Matcher Setup Source: https://vitest.dev/guide/snapshot Example of registering custom snapshot matchers using `expect.extend` and Vitest's snapshot composables. ```typescript import { expect, Snaphsots } from 'vitest' expect.extend({ toMatchMyDomainSnapshot(received: unknown) { return Snaphsots.toMatchDomainSnapshot.call(this, myAdapter, received) }, toMatchMyDomainInlineSnapshot(received: unknown, inlineSnapshot?: string) { return Snaphsots.toMatchDomainInlineSnapshot.call( this, myAdapter, received, inlineSnapshot, ) }, }) ``` -------------------------------- ### example.test.js Source: https://vitest.dev/guide/mocking/modules Importing the example module as a namespace object. ```javascript import * as exampleObject from './example.js' ``` -------------------------------- ### Importing Original of Mocked Package Source: https://vitest.dev/guide/migration Example showing the replacement of Jest's requireActual with Vitest's vi.importActual. ```typescript const { cloneDeep } = jest.requireActual('lodash/cloneDeep') // [!code --] const { cloneDeep } = await vi.importActual('lodash/cloneDeep') // [!code ++] ``` -------------------------------- ### read-hello-world.js Source: https://vitest.dev/guide/mocking/file-system A simple function to read the content of a file. ```ts import { readFileSync } from 'node:fs' export function readHelloWorld(path) { return readFileSync(path, 'utf-8') } ``` -------------------------------- ### Deprecated API Usage Source: https://vitest.dev/guide/migration Example of how to correctly pass options to test and describe functions after deprecated APIs were removed. ```typescript test('example', () => { /* ... */ }, { retry: 2 }) // [!code --] test('example', { retry: 2 }, () => { /* ... */ }) // [!code ++] ``` -------------------------------- ### Cleanup with beforeEach return value Source: https://vitest.dev/guide/learn/setup-teardown Shows how `beforeEach` can return a cleanup function, which is executed after each test, useful for closely related setup and teardown. ```javascript import { beforeEach } from 'vitest' beforeEach(() => { const server = startServer() return () => { server.close() } }) ``` -------------------------------- ### Parallel & Sequential projects Source: https://vitest.dev/guide/migration Example of configuring parallel and sequential test execution across different projects in Vitest. ```typescript import { defineConfig } from 'vitest/config' export default defineConfig({ test: { projects: [ { name: 'Parallel', exclude: ['**.sequential.test.ts'], }, { name: 'Sequential', include: ['**.sequential.test.ts'], fileParallelism: false, }, ], }, }) ``` -------------------------------- ### Benchmarking Example Source: https://vitest.dev/guide/features This code snippet illustrates how to set up benchmark tests using Vitest and Tinybench to compare performance. ```ts import { bench, describe } from 'vitest' describe('sort', () => { bench('normal', () => { const x = [1, 5, 4, 2, 3] x.sort((a, b) => { return a - b }) }) bench('reverse', () => { const x = [1, 5, 4, 2, 3] x.reverse().sort((a, b) => { return a - b }) }) }) ``` -------------------------------- ### Runtime Tag Checking Source: https://vitest.dev/guide/test-tags Example of using `TestRunner.matchesTags` to conditionally run setup logic based on active tags filters. ```typescript import { beforeAll, TestRunner } from 'vitest' beforeAll(async () => { // Seed database when "vitest --tags-filter db" is used if (TestRunner.matchesTags(['db'])) { await seedDatabase() } }) ``` -------------------------------- ### example.js Source: https://vitest.dev/guide/mocking/modules An example JavaScript module exporting a function and a constant. ```javascript export function answer() { // ... return 42 } export const variable = 'example' ``` -------------------------------- ### Custom Snapshot Matchers (Inline) Source: https://vitest.dev/guide/migration Example of migrating inline custom snapshot matchers from 'jest-snapshot' to Vitest's 'Snapshots'. ```typescript const { toMatchInlineSnapshot } = require('jest-snapshot') // [!code --] import { Snapshots } from 'vitest' // [!code ++] const { toMatchInlineSnapshot } = Snapshots // [!code ++] expect.extend({ toMatchTrimmedInlineSnapshot(received: string, inlineSnapshot?: string) { return toMatchInlineSnapshot.call(this, received.slice(0, 10), inlineSnapshot) }, }) ``` -------------------------------- ### Example usage of key-value snapshots Source: https://vitest.dev/guide/snapshot Demonstrates how to use the custom `toMatchKvSnapshot` and `toMatchKvInlineSnapshot` matchers. ```typescript import { expect, test } from 'vitest' test('user data', () => { const user = { name: 'Alice', score: '42' } expect(user).toMatchKvSnapshot() }) test('user data inline', () => { const user = { name: 'Alice', age: 100, score: '42' } expect(user).toMatchKvInlineSnapshot(` name=Alice score=/\\d+/ `) }) ``` -------------------------------- ### CLI Example Source: https://vitest.dev/config/browser/enabled Enabling browser mode via CLI with additional options. ```sh vitest --browser.enabled --browser.headless ``` -------------------------------- ### Node CLI options per project Source: https://vitest.dev/guide/migration Example of setting Node.js CLI options, such as environment files, on a per-project basis in Vitest. ```typescript import { defineConfig } from 'vitest/config' export default defineConfig({ test: { projects: [ { name: 'Production env', execArgv: ['--env-file=.env.prod'] }, { name: 'Staging env', execArgv: ['--env-file=.env.staging'] }, ], }, }) ``` -------------------------------- ### Coverage ignore start/stop Hints Source: https://vitest.dev/blog/vitest-4-1 Examples of using /* istanbul ignore start/stop */ and /* v8 ignore start/stop */ comments to exclude lines from code coverage. ```typescript /* istanbul ignore start -- @preserve */ if (parameter) { console.log('Ignored') } else { console.log('Ignored') } /* istanbul ignore stop -- @preserve */ console.log('Included') /* v8 ignore start -- @preserve */ if (parameter) { console.log('Ignored') } else { console.log('Ignored') } /* v8 ignore stop -- @preserve */ console.log('Included') ``` -------------------------------- ### Browser Provider Configuration Update Source: https://vitest.dev/guide/migration Example demonstrating the update to the browser provider configuration, changing from a string to an object with factory options. ```ts import { playwright } from '@vitest/browser-playwright' // [!code ++] export default defineConfig({ test: { browser: { provider: 'playwright', // [!code --] provider: playwright({ // [!code ++] launchOptions: { // [!code ++] slowMo: 100, // [!code ++] }, // [!code ++] }), // [!code ++] instances: [ { browser: 'chromium', launch: { // [!code --] slowMo: 100, // [!code --] }, // [!code --] }, ], }, }, }) ``` -------------------------------- ### vitest.config.js example merging with Vite config Source: https://vitest.dev/config This example illustrates how to merge a separate Vitest configuration with an existing Vite configuration file. ```js import { defineConfig, mergeConfig } from 'vitest/config' import viteConfig from './vite.config' export default mergeConfig(viteConfig, defineConfig({ test: { exclude: ['packages/template/*'], }, })) ``` -------------------------------- ### Standalone Mode with Filename Filter - package.json Scripts Source: https://vitest.dev/guide/migration Example of configuring `package.json` scripts for Vitest standalone mode with filename filtering. ```json { "scripts": { "test:dev": "vitest --standalone" } } ``` ```bash # Start Vitest in standalone mode, without running any files on start $ pnpm run test:dev # Run math.test.ts immediately $ pnpm run test:dev math.test.ts ```