Vitest filter by file path
Run tests by file path using vitest followed by filename patterns. Examples: `vitest user` runs files containing 'user', `vitest user auth` runs multiple patterns, `vitest src/user.test.ts` runs a specific file, `vitest src/user.test.ts:25` runs from a specific line number.
Vitest filter by test name
Filter tests using the -t flag or --testNamePattern flag with test names or regex patterns. Examples: `vitest -t "login"` matches tests with 'login' in the name, `vitest --testNamePattern "should.*work"` uses regex patterns, `vitest -t "/user|auth/"` matches either pattern.
Vitest --changed flag for modified files
Run tests only for files that have changed. `vitest --changed` runs tests for uncommitted changes, `vitest --changed HEAD~1` runs tests changed since a specific commit, `vitest --changed abc123` runs tests changed since commit abc123, `vitest --changed origin/main` runs tests changed since a branch.
Vitest related files filtering
Run tests that import specific files using `vitest related src/utils.ts src/api.ts --run`. This is useful with lint-staged configuration to run only tests importing files that changed. Example lint-staged config: `'*.{ts,tsx}': 'vitest related --run'` in .lintstagedrc.js.
Vitest .only focus tests
Use test.only() or describe.only() to run only specific tests or suites. Example: `test.only('only this runs', () => {})` or `describe.only('only this suite', () => { test('runs', () => {}) })`. In CI environments, .only throws an error unless configured with `allowOnly: true` in the defineConfig test options.
Vitest skip tests
Skip tests using test.skip(), test.skipIf(), test.runIf(), or dynamic skip. Examples: `test.skip('skipped', () => {})`, `test.skipIf(process.env.CI)('not in CI', () => {})`, `test.runIf(!process.env.CI)('local only', () => {})`, or within a test: `test('dynamic', ({ skip }) => { skip(someCondition, 'reason') })`.
Vitest tags for filtering tests
Add tags to tests using the tags option. Example: `test('database test', { tags: ['db'] }, () => {})` or `test('slow test', { tags: ['slow', 'integration'] }, () => {})`. Run tagged tests with `vitest --tags db` or `vitest --tags "db,slow"` or `vitest --tags db --tags slow`. Configure allowed tags in defineConfig with `test: { tags: ['db', 'slow', 'integration'], strictTags: true }` to fail on unknown tags.
Vitest include and exclude patterns
Configure test file patterns in defineConfig. The include field specifies test file patterns (default `['**/*.{test,spec}.{ts,tsx}']`), exclude field specifies patterns to exclude (examples: `'**/node_modules/**'`, `'**/e2e/**'`, `'**/*.skip.test.ts'`), and includeSource field includes source files for in-source testing (example: `['src/**/*.ts']`).
Vitest watch mode filtering
In watch mode, press `p` to filter by filename pattern, `t` to filter by test name pattern, `a` to run all tests, or `f` to run only failed tests.
Vitest project filtering
Run specific projects using the --project flag. Examples: `vitest --project unit` runs only the unit project, `vitest --project integration --project e2e` runs both integration and e2e projects.
Vitest environment-based filtering
Conditionally skip or run tests based on environment variables. Examples: `describe.skipIf(isCI)('local only tests', () => {})` skips tests in CI, `describe.runIf(isDev)('dev tests', () => {})` runs only in development mode.
Vitest combining multiple filters
Multiple filters can be combined. Examples: `vitest user -t "login" --changed` combines file pattern, test name, and changed files filters. `vitest related src/auth.ts --run` combines related files filtering with run mode.
Vitest list command
List tests without running them using `vitest list` to show all test names, `vitest list -t "user"` to filter by name, `vitest list --filesOnly` to show only file paths, or `vitest list --json` for JSON output.
Create and configure mock functions with vi.fn()
Mock functions are created with vi.fn(). They can be called and tracked for calls. You can configure mock return values with mockReturnValue(value), mockReturnValueOnce(value), mockResolvedValue(value), or mockRejectedValue(error). You can set mock implementations with mockImplementation(fn) or mockImplementationOnce(fn). Example: const fn = vi.fn(); fn('hello'); expect(fn).toHaveBeenCalledWith('hello');
Spy on object methods with vi.spyOn()
Use vi.spyOn(object, 'methodName') to spy on existing methods. The spy tracks calls while optionally replacing the implementation. You can restore the original implementation with mockRestore(). Example: const spy = vi.spyOn(cart, 'getTotal'); spy.mockReturnValue(200); expect(cart.getTotal()).toBe(200); spy.mockRestore();
Mock entire modules with vi.mock()
vi.mock() is hoisted to the top of the file before imports. It takes a module path and a factory function that returns the mocked exports. Example: vi.mock('./api', () => ({ fetchUser: vi.fn(() => ({ id: 1, name: 'Mock' })), }));
Partial module mocking with importOriginal
To mock only some exports and keep others real, use vi.mock() with a factory that calls importOriginal(). Example: vi.mock('./utils', async (importOriginal) => { const actual = await importOriginal(); return { ...actual, specificFunction: vi.fn() }; })
Auto-mock modules while spying on implementation
Use vi.mock(path, { spy: true }) to keep the real implementation but spy on calls. This allows you to verify that functions are called without replacing their behavior. Example: vi.mock('./calculator', { spy: true }); The function add(1, 2) still returns 3 but expect(add).toHaveBeenCalledWith(1, 2) works.
Manual mocks using __mocks__ directory
Create a __mocks__ directory next to or inside the module directory. Place mock files there with the same name as the module. For 'axios', create src/__mocks__/axios.ts. For './api/client', create src/api/__mocks__/client.ts. Call vi.mock() with the path and no factory function.
Dynamic mocking with vi.doMock() for non-hoisted mocks
Use vi.doMock() inside tests for dynamic mocking that is not hoisted. This allows you to mock modules differently in different tests. Pair it with vi.doUnmock() to clean up. Example: vi.doMock('./config', () => ({ apiUrl: 'http://test.local' })); const { apiUrl } = await import('./config');
Setup and teardown fake timers
Call vi.useFakeTimers() in beforeEach() to activate fake timers, and vi.useRealTimers() in afterEach() to restore real timers. This prevents test pollution and allows you to control time in tests.
Advance fake timers with vi.advanceTimersByTime()
vi.advanceTimersByTime(ms) moves fake time forward by the given milliseconds and runs callbacks scheduled for that time. vi.runAllTimers() runs all pending timers immediately. vi.runOnlyPendingTimers() runs only currently pending timers. vi.advanceTimersToNextTimer() advances to the next scheduled timer.
Async timer advancement with vi.advanceTimersByTimeAsync()
Use vi.advanceTimersByTimeAsync(ms) in async tests to advance fake timers while properly awaiting Promise resolution. This ensures promises scheduled within timer callbacks resolve correctly. Example: await vi.advanceTimersByTimeAsync(100);
Mock system time with vi.setSystemTime()
vi.setSystemTime() sets the fake system time to a specific date. new Date() will then return the mocked time. Call vi.useRealTimers() to restore real time. Example: vi.setSystemTime(new Date('2024-01-01')); expect(new Date().getFullYear()).toBe(2024);
Mock global functions with vi.stubGlobal()
Use vi.stubGlobal(name, value) to mock global functions like fetch. Restore all stubbed globals with vi.unstubAllGlobals(). Example: vi.stubGlobal('fetch', vi.fn(() => Promise.resolve({ json: () => ({ data: 'mock' }) })));
Mock environment variables with vi.stubEnv()
Use vi.stubEnv(name, value) to mock environment variables accessed via import.meta.env. Restore all stubbed env vars with vi.unstubAllEnvs(). Example: vi.stubEnv('API_KEY', 'test-key'); expect(import.meta.env.API_KEY).toBe('test-key');
Clear, reset, and restore mocks
mockClear() clears call history but keeps the implementation. mockReset() clears history and restores default implementation. mockRestore() restores the original for spies. For all mocks globally: vi.clearAllMocks(), vi.resetAllMocks(), vi.restoreAllMocks().
Auto-reset mocks between tests via config
In vitest.config.ts, configure test options: clearMocks (clear before each test), mockReset (reset before each test), restoreMocks (restore after each test), unstubEnvs (restore env vars), and unstubGlobals (restore globals).
Reference mock functions in mock factories with vi.hoisted()
Use vi.hoisted() to define variables before vi.mock() is hoisted. This allows you to reference the same mock instance in the factory. Example: const mockFn = vi.hoisted(() => vi.fn()); vi.mock('./module', () => ({ getData: mockFn }));
Key mocking rules: hoisting, restoration, and spy mode
vi.mock() is hoisted and called before imports. Always restore mocks to avoid test pollution. Use { spy: true } to keep real implementation while tracking calls. Use vi.doMock() for dynamic non-hoisted mocking.