new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Vitest · API reference · all subjects

vi object/methods

131 notes in this subject, read out of this brain and free to use. This is page 1 of 3.

import function signature

The import function is a generic function that takes a moduleId string parameter and returns a Promise of the generic type T. The function signature is: function import<T>(moduleId: string): Promise<T>

vi.defineHelper wraps functions to improve stack traces

vi.defineHelper wraps a function so that Vitest removes its internals from the stack trace and points the error back to the call site instead. This is useful for custom assertion libraries and reusable test utilities where the call site is more meaningful than the implementation. Example: const assertPair = vi.defineHelper((a, b) => { expect(a).toEqual(b) }) - the error will point to where assertPair is called, not inside the function.

mockThrow and mockThrowOnce methods for error throwing

The mockThrow method makes a mock throw an error without wrapping it in a function. mockThrow(new Error('error message')) replaces the previous pattern of mockImplementation(() => { throw new Error(...) }). mockThrowOnce is also available for single-use error throwing.

mockRestore restores original object descriptors

The mockRestore method has signature: function mockRestore(): Mock<T>. It does what mockReset does and restores the original descriptors of spied-on objects if the mock was created with vi.spyOn. On a vi.fn() mock, mockRestore is identical to mockReset.

mockName sets internal mock name

The mockName method has signature: function mockName(name: string): Mock<T>. It sets the internal mock name, which is useful for identifying the mock when an assertion fails.

getMockName signature and behavior

The getMockName method has signature: function getMockName(): string. It returns the name assigned to the mock with the .mockName(name) method. By default, vi.fn() mocks return 'vi.fn()', while spies created with vi.spyOn keep the original name.

mockImplementationOnce signature and behavior

The mockImplementationOnce method has signature: function mockImplementationOnce(fn: T): Mock<T>. It accepts a function to be used as the mock implementation for the next call only. This method can be chained to produce different results for multiple function calls. When the mocked function runs out of implementations, it invokes the default implementation set with vi.fn(() => defaultValue) or .mockImplementation(() => defaultValue).

mock.settledResults contains resolved or rejected values

The mock.settledResults property has type: MockSettledResult<Awaited<ReturnType<T>>>[] where MockSettledResult is one of: MockSettledResultIncomplete (type 'incomplete'), MockSettledResultFulfilled (type 'fulfilled'), or MockSettledResultRejected (type 'rejected'). It contains all values that were resolved or rejected by the function. If the function returned non-promise values, the value is kept as is but the type will still indicate fulfilled or rejected. Until the value is resolved or rejected, the type will be 'incomplete'.

mockClear clears call history but keeps implementation

The mockClear method has signature: function mockClear(): Mock<T>. It clears all information about every call and resets all .mock properties to their initial state, but does not reset mock implementations. It is useful for cleaning up mocks between assertions.

mockThrow throws value whenever mock is called

The mockThrow method has signature: function mockThrow(value: unknown): Mock<T>. It accepts a value that will be thrown whenever the mock function is called. Available since Vitest 4.1.0.

mockImplementation signature and behavior

The mockImplementation method has signature: function mockImplementation(fn: T): Mock<T>. It accepts a function to be used as the mock implementation. TypeScript expects the arguments and return type to match those of the original function. If the implementation is a class, the mock's prototype is re-pointed to the implementation's prototype.

mockReturnThis returns this context without invoking implementation

The mockReturnThis method has signature: function mockReturnThis(): Mock<T>. It returns the this context from the method without invoking the actual implementation. This is a shorthand for spy.mockImplementation(function () { return this }).

vi.fn creates mock functions

The vi.fn method creates a mock function to track its execution. You can call the mock function and access its call history through the .mock property.

mockResolvedValue resolves with value for async function

The mockResolvedValue method has signature: function mockResolvedValue(value: Awaited<ReturnType<T>>): Mock<T>. It accepts a value that will be resolved when the async function is called. TypeScript will only accept values that match the return type of the original function.

mockRejectedValueOnce rejects with value for next call only

The mockRejectedValueOnce method has signature: function mockRejectedValueOnce(value: unknown): Mock<T>. It accepts a value that will be rejected during the next function call only. If chained, each consecutive call will reject the specified value.

mock.instances contains instances created with new keyword

The mock.instances property has type: ReturnType<T>[]. It is an array containing all instances that were created when the mock was called with the new keyword. This is the actual context (this) of the function, not a return value. If you return a value from the constructor, it will not be in the instances array but instead inside results.

vi.spyOn tracks properties on existing objects

The vi.spyOn method allows you to track a property on an already created object. It takes an object and a property name, and returns a spy that tracks calls to that property.

mock.invocationCallOrder contains execution order

The mock.invocationCallOrder property has type: number[]. It returns the order of the mock function's execution as an array of numbers that are shared between all defined mocks.

mockResolvedValueOnce resolves with value for next call only

The mockResolvedValueOnce method has signature: function mockResolvedValueOnce(value: Awaited<ReturnType<T>>): Mock<T>. It accepts a value that will be resolved during the next function call only. TypeScript will only accept values that match the return type of the original function. If chained, each consecutive call will resolve the specified value.

mock.lastCall contains arguments of the last call

The mock.lastCall property has type: Parameters<T> | undefined. It contains the arguments of the last call. If the mock wasn't called, it returns undefined.

mock.calls contains all arguments for each call

The mock.calls property has type: Parameters<T>[]. It is an array containing all arguments for each call. One item of the array is the arguments of that single call. Note that Vitest always stores objects by reference, meaning if object properties change after the call, assertions like toHaveBeenCalledWith will reflect the changed values, not the original call values.

mockThrowOnce throws value for next call only

The mockThrowOnce method has signature: function mockThrowOnce(value: unknown): Mock<T>. It accepts a value that will be thrown during the next function call only. If chained, every consecutive call will throw the specified value. Available since Vitest 4.1.0.

getMockImplementation signature and behavior

The getMockImplementation method has signature: function getMockImplementation(): T | undefined. It returns the current mock implementation if there is one. If the mock was created with vi.fn, it returns the provided method as the mock implementation. If created with vi.spyOn, it returns undefined unless a custom implementation is provided.

mockReturnValueOnce returns value for next call only

The mockReturnValueOnce method has signature: function mockReturnValueOnce(value: ReturnType<T>): Mock<T>. It accepts a value that will be returned during the next function call only. When the mocked function runs out of implementations, it invokes the default implementation set with vi.fn(() => defaultValue) or .mockImplementation(() => defaultValue).

mockReturnValue returns value whenever mock is called

The mockReturnValue method has signature: function mockReturnValue(value: ReturnType<T>): Mock<T>. It accepts a value that will be returned whenever the mock function is called. TypeScript will only accept values that match the return type of the original function.

mock.results contains return values and thrown errors

The mock.results property has type: MockResult<ReturnType<T>>[]. It is an array containing all values that were returned from or thrown by the function. Each item is an object with properties type and value. Available types are 'return' (function returned without throwing), 'throw' (function threw a value), or 'incomplete' (function did not finish running yet). If the function returned a Promise, the result type will always be 'return' even if the promise was rejected.

Shorthand mock methods cannot be used on mocked classes

Shorthand methods like mockReturnValue, mockReturnValueOnce, mockResolvedValue, and mockThrow cannot be used on a mocked class because class constructors have unintuitive behaviour regarding return values. Use mockImplementation with class syntax instead, or use mockImplementation for custom constructor logic.

withImplementation temporarily overrides mock implementation

The withImplementation method has two signatures: function withImplementation(fn: T, cb: () => void): Mock<T> and function withImplementation(fn: T, cb: () => Promise<void>): Promise<Mock<T>>. It overrides the original mock implementation temporarily while the callback is being executed, then restores the original implementation afterward. This method takes precedence over mockImplementationOnce.

mockRejectedValue rejects with error on async call

The mockRejectedValue method has signature: function mockRejectedValue(value: unknown): Mock<T>. It accepts an error that will be rejected when an async function is called.

mock.contexts contains this values for each call

The mock.contexts property has type: ThisParameterType<T>[]. It is an array of this values used during each call to the mock function.

Mock function .length property is inherited but not overridden

Vitest spies inherit the implementation's length property when initialized. However, if the implementation is changed later with mockImplementation, the length property does not update to reflect the new implementation's length.

How to stub return values with vi.fn

To stub return values in Vitest, use vi.fn().mockReturnValue(value) to return a value every time the mock is called, or vi.fn().mockReturnValueOnce(value) to return a value only for the next call. For async functions, use mockResolvedValue(value) or mockResolvedValueOnce(value). You can also pass an implementation function directly to vi.fn(impl) or use mockImplementation(impl).

Mock objects stored by reference warning

Vitest always stores objects by reference in all properties of the mock state. This means if object properties are changed after being passed to a mock, assertions like toHaveBeenCalledWith will not pass because they check against the modified object. To avoid this, use structuredClone to clone the argument when storing it.

mockReset clears and resets mock implementation

The mockReset method has signature: function mockReset(): Mock<T>. It does what mockClear does and resets the mock implementation. This also resets all 'once' implementations. Resetting a mock from vi.fn() sets the implementation to an empty function returning undefined. Resetting vi.fn(impl) resets the implementation to impl. The mock's prototype chain reverts to original for vi.fn(impl) and vi.spyOn, or to a plain object for vi.fn().

vi.importMock - function signature

vi.importMock<T>(path: string): Promise<MaybeMockedDeep<T>> imports a module with all of its properties (including nested properties) mocked. Follows the same rules that vi.mock does.

vi.importActual - function signature

vi.importActual<T>(path: string): Promise<T> imports module, bypassing all checks if it should be mocked. Can be useful if you want to mock module partially.

vi.mocked example with partial and deep

Example using vi.mocked with partial and deep options: import * as example from './example'; vi.mock('./example'); test('mock return value with deep partial typing', async () => { vi.mocked(example.getUser, { partial: true, deep: true }).mockReturnValue({ address: { city: 'Los Angeles' } }); expect(example.getUser().address.city).toBe('Los Angeles'); });

vi.mocked - partial and deep options

When partial is true, vi.mocked will expect a Partial<T> as a return value. By default, this will only make TypeScript believe that the first level values are mocked. You can pass down { deep: true } as a second argument to tell TypeScript that the whole object is mocked. You can pass down { partial: true, deep: true } to make nested objects also partial recursively.

vi.doMock - Explicit Resource Management

In environments that support Explicit Resource Management, you can use using on the value returned from vi.doMock() to automatically call vi.doUnmock() on the mocked module when the containing block is exited. Example: it('uses a mocked version of my-module', () => { using _mockDisposable = vi.doMock('my-module'); const myModule = await import('my-module'); });

vi.doMock example with variable access

Example of vi.doMock accessing variables: import { beforeEach, test } from 'vitest'; import { increment } from './increment.js'; let mockedIncrement = 100; beforeEach(() => { vi.doMock('./increment.js', () => ({ increment: () => ++mockedIncrement })); }); test('importing the next module imports mocked one', async () => { expect(increment(1)).toBe(2); const { increment: mockedIncrement } = await import('./increment.js'); expect(mockedIncrement(1)).toBe(101); expect(mockedIncrement(1)).toBe(102); });

vi.doMock - non-hoisted behavior

vi.doMock is not hoisted to the top of the file, so you can reference variables in the global file scope. The next dynamic import of the module will be mocked. This will not mock modules that were imported before this was called. All static imports in ESM are always hoisted, so putting vi.doMock before static import will not force it to be called before the import.

vi.doMock - function signature

vi.doMock has two overload signatures: function doMock(path: string, factory?: MockOptions | MockFactory<unknown>): Disposable and function doMock<T>(module: Promise<T>, factory?: MockFactory<T>): Disposable. It returns a Disposable object.

vi.mock - reference to hoisted variables

vi.mock is hoisted to the top of the file, which means you cannot use any variables inside the factory that are defined outside the factory. You can reference variables defined by vi.hoisted method if it was declared before vi.mock. Example: const mocks = vi.hoisted(() => { return { namedExport: vi.fn() }; }); vi.mock('./path/to/module.js', () => { return { namedExport: mocks.namedExport }; });

vi.mock - import keyword only

vi.mock works only for modules that were imported with the import keyword. It doesn't work with require. In order to hoist vi.mock, Vitest statically analyzes your files, which means vi that was not directly imported from the vitest package cannot be used. Use vi.mock with vi imported from vitest, or enable the globals config option.

vi.mock - setup files limitation

Vitest will not mock modules that were imported inside a setup file because they are cached by the time a test file is running. You can call vi.resetModules() inside vi.hoisted to clear all module caches before running a test file.

vi.mock - __mocks__ folder support

If there is a __mocks__ folder alongside a file that you are mocking, and the factory is not provided, Vitest will try to find a file with the same name in the __mocks__ subfolder and use it as an actual module. If you are mocking a dependency, Vitest will try to find a __mocks__ folder in the root of the project (default is process.cwd()). You can tell Vitest where the dependencies are located through the deps.moduleDirectories config option.

vi.mock - default export caveat

If you are mocking a module with default export, you will need to provide a default key within the returned factory function object. This is an ES module-specific caveat. Example: vi.mock('./path/to/module.js', () => { return { default: { myDefaultKey: vi.fn() }, namedExport: vi.fn() }; })

vi.mock - module promise signature

Vitest supports a module promise instead of a string in vi.mock and vi.doMock methods for better IDE support. When the file is moved, the path will be updated, and importOriginal inherits the type automatically. Using this signature will also enforce factory return type to be compatible with the original module (keeping exports optional). Example: vi.mock(import('./path/to/module.js'), async (importOriginal) => { const mod = await importOriginal(); return { ...mod, total: vi.fn() }; })

vi.mock spy example

Example using vi.mock with spy: true: import { calculator } from './src/calculator.ts'; vi.mock('./src/calculator.ts', { spy: true }); const result = calculator(1, 2); expect(result).toBe(3); expect(calculator).toHaveBeenCalledWith(1, 2); expect(calculator).toHaveReturnedWith(3);

vi.mock - spy option

If the factory is not provided, you can provide an object with a spy property instead. If spy is true, then Vitest will automock the module as usual, but it won't override the implementation of exports. This is useful if you just want to assert that the exported method was called correctly by another method.

vi.mock - hoisting behavior

The call to vi.mock is hoisted, so it doesn't matter where you call it - it will always be executed before all imports. If you need to reference variables outside of its scope, you can define them inside vi.hoisted and reference them inside vi.mock. It is recommended to use vi.mock or vi.hoisted only inside test files.

vi.mock - function signature

vi.mock has two overload signatures: function mock(path: string, factory?: MockOptions | MockFactory<unknown>): void and function mock<T>(module: Promise<T>, factory?: MockFactory<T>): void. MockOptions interface has optional spy: boolean property. MockFactory<T> is a function type: (importOriginal: () => T): unknown.

vi.isWhenChain - type guard for When chains

vi.isWhenChain(input: object): input is When returns true if the given value is a When chain created by vi.when. If using TypeScript, it will also narrow down its type. Example: const spy = vi.fn(); const w = vi.when(spy).calledWith(1).thenReturn(0); expect(vi.isWhenChain(w)).toBe(true); expect(vi.isWhenChain(spy)).toBe(false);

vi.mocked - function signature

vi.mocked has two overload signatures: function mocked<T>(object: T, deep?: boolean): MaybeMockedDeep<T> and function mocked<T>(object: T, options?: { partial?: boolean; deep?: boolean }): MaybePartiallyMockedDeep<T>. It is a type helper for TypeScript that returns the object that was passed.

vi.when basic example

Example of vi.when basic usage: const spy = vi.fn(); vi.when(spy).calledWith(1).thenReturn('one').calledWith(2).thenReturn('two'); expect(spy(1)).toBe('one'); expect(spy(2)).toBe('two');

vi.when example with fallback and times

Example showing vi.when with times option: const spy = vi.fn<(key: string) => string>(); vi.when(spy).calledWith('theme').thenReturn('light').thenReturn('dark', { times: 2 }); expect(spy('theme')).toBe('dark'); expect(spy('theme')).toBe('dark'); expect(spy('theme')).toBe('light');

vi.when - times option

The optional times option in BehaviorOptions limits how many times a behavior applies before being exhausted. Behaviors registered for the same arguments are consumed last-in-first-out: the most recently registered behavior is tried first, and once exhausted, earlier ones act as fallbacks.

vi.importActual example

Example using vi.importActual: vi.mock('./example.js', async () => { const originalModule = await vi.importActual('./example.js'); return { ...originalModule, get: vi.fn() }; })

vi.when - available then* methods

Available then* methods on a When chain: thenReturn(value, options?) returns value; thenReturnOnce(value) returns value once, then falls back; thenThrow(error, options?) throws error; thenThrowOnce(error) throws error once, then falls back; thenResolve(value, options?) returns a resolved Promise with value; thenResolveOnce(value) resolves once, then falls back; thenReject(error, options?) returns a rejected Promise with error; thenRejectOnce(error) rejects once, then falls back.

vi.when - per-argument spy behavior

vi.when(spy, options?) defines per-argument behaviors on a spy, replacing its implementation for the duration of the when chain. It returns a When object. Call .calledWith(...args) on the returned object to specify which call arguments to match, then chain one or more then* methods to declare what the spy should return, throw, or resolve when invoked with those arguments. Arguments are matched with deep equality and support asymmetric matchers such as expect.any(). The optional onUnmatched option in WhenOptions changes behavior when called with unmatched arguments: 'passthrough' (default) delegates to the spy's original implementation, 'throw' throws an error listing the unmatched arguments, or a function that is called with the unmatched arguments and its return value is used.

Give your agent this brain