### Install with yarn Source: https://github.com/eratio08/vitest-mock-extended/blob/main/README.md Install vitest-mock-extended as a dev dependency using yarn. ```bash yarn add vitest-mock-extended --dev ``` -------------------------------- ### Install with npm Source: https://github.com/eratio08/vitest-mock-extended/blob/main/README.md Install vitest-mock-extended as a dev dependency using npm. ```bash npm install vitest-mock-extended --save-dev ``` -------------------------------- ### Mock a module with vi.mock and use mocked in a test Source: https://github.com/eratio08/vitest-mock-extended/blob/main/README.md Complete example of mocking a module using vi.mock with a factory that returns a mock object, then importing the mock and using mocked to access the mock in a test. The example shows the pattern of defining the mock inside vi.mock due to hoisting, and then using the mocked helper to get a typed mock. ```typescript // Mock a module // @/libs/example.mock.ts import { mock } from "vitest-mock-extended"; import { ExampleClient } from "@/libs/example"; vi.mock(import("@/libs/example"), async (importOriginal) => { const actual = await importOriginal(); return { ...actual, // Due to vi.mock being hoisted, we have to mock here directly instead of // defining an exampleMock outside and assign it to example example: mock(), }; }); // Use the mocked object import "@/libs/example.mock"; // Mock out the actual client import { mocked } from "vitest-mock-extended"; import { example } from "@/libs/example"; const exampleMock = mocked(example); test("send notification", () => { example.function.mockResolvedValue(xxx); ... } ``` -------------------------------- ### stub usage example Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/api-reference/mock.md Example of creating a stub with stub() and verifying that property access returns a function without calling real methods. ```typescript import { stub } from 'vitest-mock-extended' interface Config { read: (k: string) => string } const config = stub() typeof config.read // 'function' — real methods are not called ``` -------------------------------- ### Example: mock with partial implementation Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/api-reference/mock.md Shows how to create a mock with a partial implementation, preserving real method implementations and using `calledWith` to set return values. ```typescript import { mock } from 'vitest-mock-extended'; interface PartyProvider { getPartyType: () => string getSongs: (type: string) => string[] start: (type: string) => void } const provider = mock({ getPartyType: () => 'west coast party' }) provider.getPartyType() // -> 'west coast party' (from implementation) provider.getSongs.calledWith('jazz').mockReturnValue(['Take Five']) provider.getSongs('jazz') // -> ['Take Five'] provider.start('disco party') // records the call on a vi.fn() ``` -------------------------------- ### Capturing multiple arguments with captor Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/api-reference/matchers.md Example showing how to capture multiple arguments across multiple calls. The captor records each matched argument in values and the last one in value. ```ts import { captor, anyString, mock } from 'vitest-mock-extended' interface Audit { log: (level: string, message: string) => void } const audit = mock() const levelCaptor = captor() audit.log.calledWith(levelCaptor, anyString()).mockImplementation(() => {}) audit.log('error', 'disk full') audit.log('warn', 'cache miss') console.log(levelCaptor.values) // ['error', 'warn'] console.log(levelCaptor.value) // 'warn' ``` -------------------------------- ### Mock an interface and return type Source: https://github.com/eratio08/vitest-mock-extended/blob/main/README.md Example test suite showing how to mock an interface, set return values, and use fallbackMockImplementation. Includes three test cases: mocking an interface, mocking a return type, and specifying a fallback implementation. ```ts import { mock } from 'vitest-mock-extended'; interface PartyProvider { getPartyType: () => string; getSongs: (type: string) => string[]; start: (type: string) => void; } describe('Party Tests', () => { test('Mock out an interface', () => { const mock = mock(); mock.start('disco party'); expect(mock.start).toHaveBeenCalledWith('disco party'); }); test('mock out a return type', () => { const mock = mock(); mock.getPartyType.mockReturnValue('west coast party'); expect(mock.getPartyType()).toBe('west coast party'); }); test('Can specify fallbackMockImplementation', () => { const mockObj = mock( {}, { fallbackMockImplementation: () => { throw new Error('not mocked'); }, } ); expect(() => mockObj.getSomethingWithArgs(1, 2)).toThrowError('not mocked'); }); }); ``` -------------------------------- ### Creating a Mock Function with mockFn() Source: https://github.com/eratio08/vitest-mock-extended/blob/main/README.md Use mockFn() to create a vi.fn() that includes the calledWith() extension. The example defines a function type and then uses calledWith() to set a return value. ```typescript type MyFn = (x: number, y: number) => Promise; const fn = mockFn(); fn.calledWith(1, 2).mockReturnValue('str'); ``` -------------------------------- ### mockedFn usage example Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/api-reference/mock.md Example of using mockedFn to type a mock function from a vi.mock factory and call .calledWith(). ```typescript import { mockedFn } from 'vitest-mock-extended' import { lookup } from './mock-factory' // created with mockFn in a vi.mock factory const fn = mockedFn(lookup) fn.calledWith('key').mockReturnValue(42) ``` -------------------------------- ### mockReset usage example Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/api-reference/mock.md Example showing how to use mockReset to clear call history and remove all implementations. After reset, the mock returns undefined until a new implementation is registered. ```typescript import { mock, mockReset } from 'vitest-mock-extended' interface Auth { login: (u: string, p: string) => string } const auth = mock() auth.login.calledWith('u', 'p').mockReturnValue('token') auth.login('u', 'p') // -> 'token' mockReset(auth) auth.login('u', 'p') // -> undefined (all implementations removed) auth.login.calledWith('u', 'p').mockReturnValue('token2') // can re-register ``` -------------------------------- ### matches and isA with error-aware handling Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/api-reference/matchers.md Shows matches() and isA() with error-aware handling. Unmatched arguments silently resolve to undefined unless a fallback is set; the example adds a fallback for negative priorities. ```ts import { isA, matches, mock } from 'vitest-mock-extended' class Task { constructor(readonly id: string) {} } interface Runner { dispatch: (task: Task, priority: number) => string } const runner = mock() runner.dispatch .calledWith(isA(Task), matches((p: number) => p >= 0)) .mockReturnValue('queued') runner.dispatch(new Task('t1'), 5) // -> 'queued' const result = runner.dispatch(new Task('t2'), -1) // no entry matched if (result === undefined) { // unmatched args silently resolve to undefined unless a fallback is set runner.dispatch.calledWith(isA(Task), matches((p: number) => p < 0)) .mockReturnValue('rejected') } runner.dispatch(new Task('t2'), -1) // -> 'rejected' ``` -------------------------------- ### VitestMockExtended usage example Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/api-reference/mock.md Example showing how to configure VitestMockExtended to allow mocking 'then' and resetting the config. ```typescript import { VitestMockExtended, mock } from 'vitest-mock-extended' interface Thenable { then: (cb: () => void) => void } VitestMockExtended.configure({ ignoreProps: [] }) // allow mocking 'then' const m = mock() m.then.calledWith().mockImplementation((cb) => cb()) m.then(() => console.log('invoked')) // logs 'invoked' VitestMockExtended.resetConfig() const m2 = mock() m2.then // -> undefined (default ignoreProps: ['then']) ``` -------------------------------- ### mocked usage example Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/api-reference/mock.md Example of using mocked to type a mocked module value. Shows shallow and deep flavors, and that the returned mock can be used to set return values. ```typescript import { mocked } from 'vitest-mock-extended' import { trader } from './some-module' // in a vi.mock factory (the module is hoisted, so you mock it there): // vi.mock('./some-module', () => ({ trader: mock() })) const traderMock = mocked(trader) // shallow MockProxy flavor const traderDeepMock = mocked(trader, true) // deep DeepMockProxy flavor traderMock.execute.mockReturnValue('ok') ``` -------------------------------- ### calledWith() with Matchers and Mock Return Values Source: https://github.com/eratio08/vitest-mock-extended/blob/main/README.md Shows how to use calledWith() for invocation matching with type-checked arguments and matchers like any() and anyString(). The example sets up mock return values for specific and matcher-based calls. ```typescript const provider = mock(); provider.getSongs.calledWith('disco party').mockReturnValue(['Dance the night away', 'Stayin Alive']); expect(provider.getSongs('disco party')).toEqual(['Dance the night away', 'Stayin Alive']); // Matchers provider.getSongs.calledWith(any()).mockReturnValue(['Saw her standing there']); provider.getSongs.calledWith(anyString()).mockReturnValue(['Saw her standing there']); ``` -------------------------------- ### isMockObject usage example Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/api-reference/mock.md Example of using isMockObject to narrow a value to a MockProxy and call mock methods. Shows that after the guard, value.request.mockReturnValue is valid and the mock returns the configured value. ```typescript import { isMockObject, mock, type MockProxy } from 'vitest-mock-extended' interface Service { request: (id: string) => string } const value: Service | MockProxy = mock() if (isMockObject(value)) { value.request.mockReturnValue('mocked response') } value.request('x') // -> 'mocked response' ``` -------------------------------- ### mockDeep basic usage with mockImplementation Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/api-reference/mock.md Creates a deep mock of a Car class, preserving the real value for engine.hp and mocking the start method. Without mockImplementation, reading car.engine.hp would lazily create a nested mock function instead of a number. ```typescript import { mockDeep, type DeepMockProxy } from 'vitest-mock-extended' class Engine { hp: number = 300 start(): string { return 'vroom' } } class Car { engine: Engine = new Engine() } const car: DeepMockProxy = mockDeep({ engine: { hp: 300 } }) car.engine.hp // -> 300 (preserved real value) car.engine.start.calledWith().mockReturnValue('started') car.engine.start() // -> 'started' // without mockImplementation, reading car.engine.hp would lazily // create a nested mock function instead of a number ``` -------------------------------- ### Assigning Mocks with MockProxy Type Source: https://github.com/eratio08/vitest-mock-extended/blob/main/README.md Use MockProxy when assigning a mock to a typed variable to get calledWith() and other Vitest mock APIs. The example shows a beforeEach assigning mock() to a MockProxy variable. ```typescript import { MockProxy, mock } from 'vitest-mock-extended'; describe('test', () => { let myMock: MockProxy; beforeEach(() => { myMock = mock(); }) test(() => { myMock.calledWith(1).mockReturnValue(2); ... }) }); ``` -------------------------------- ### Global Configuration Methods Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/configuration.md Global configuration methods for the vitest-mock-extended library. ```APIDOC ## VitestMockExtended.configure(config: GlobalConfig): void ### Description Sets the global configuration used by all subsequently created mocks. The provided config is shallow-merged over the default configuration, allowing you to override any settings. ### Method configure ### Parameters - **config** (GlobalConfig) - Required - The configuration object to apply. Supported keys: `ignoreProps` (array of string | number | symbol) - Optional - Property keys whose reads return `undefined` instead of lazy mock functions. Default is `['then']`. ### Example ```ts import { VitestMockExtended, mock } from 'vitest-mock-extended' // allow mocking a 'then' property VitestMockExtended.configure({ ignoreProps: [] }) const m = mock<{ then: (cb: () => void) => void }>() m.then.calledWith().mockImplementation((cb) => cb()) ``` ### Response No return value (void). ``` ```APIDOC ## VitestMockExtended.resetConfig(): void ### Description Restores the default global configuration for subsequently created mocks. After calling this, the `ignoreProps` setting returns to its default value of `['then']`. ### Method resetConfig ### Parameters None. ### Example ```ts import { VitestMockExtended, mock } from 'vitest-mock-extended' VitestMockExtended.resetConfig() const m2 = mock<{ then: (cb: () => void) => void }>() m2.then // undefined — 'then' ignored again ``` ### Response No return value (void). ``` -------------------------------- ### stub Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/api-reference/mock.md Creates a proxy object with no implementations; every property access returns a fresh vi.fn() unless the key already exists. ```APIDOC ## `stub` ### Signature ```ts const stub = (): T => { return new Proxy({} as T, { get: (obj, property: ProxiedProperty) => { if (property in obj) { return obj[property] } return vi.fn() }, }) } ``` Source: `src/Mock.ts:247–257`. ### Parameters None. ### Return type `T` — a proxy with no implementations; every property access returns a fresh `vi.fn()` (existing keys return the stored value). ### Example ```ts import { stub } from 'vitest-mock-extended' interface Config { read: (k: string) => string } const config = stub() typeof config.read // 'function' — real methods are not called ``` ``` -------------------------------- ### Import matchers from vitest-mock-extended Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/api-reference/matchers.md Import all matcher-related symbols from the package root. The comment indicates additional matchers are available. ```ts import { Matcher, CaptorMatcher, captor, any, anyString, isA, matches, /* ... */ } from 'vitest-mock-extended' ``` -------------------------------- ### Import and use mocked, mockedFn, and isMockObject APIs Source: https://github.com/eratio08/vitest-mock-extended/blob/main/README.md Shows how to import and use the mocked, mockedFn, and isMockObject helpers. Use mocked to create a mock proxy from an original object, optionally deep-mocking with a second argument. Use mockedFn to mock a function. isMockObject safely narrows a value to a MockProxy type. ```typescript // APIs import { mocked, mockedFn } from "vitest-mock-extended"; import { originalObj, originalFn} from "somewhere"; const mockedObj = mocked(originalObj); const deepMockedObj = mocked(originalObj, true); const mockedFunction = mockedFn(originalFn); ``` ```typescript import { isMockObject, type MockProxy } from "vitest-mock-extended"; const service: Service | MockProxy = getService(); if (isMockObject(service)) { service.request.mockReturnValue("mocked response"); } ``` -------------------------------- ### mockClear usage example Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/api-reference/mock.md Example showing how to use mockClear to clear call history while retaining registered implementations. After mockClear, the mock still returns the registered value. ```typescript import { mock, mockClear } from 'vitest-mock-extended' interface Repo { find: (id: string) => number } const repo = mock() repo.find.calledWith('a').mockReturnValue(1) repo.find('a') repo.find.mock.calls.length // 1 mockClear(repo) repo.find.mock.calls.length // 0 repo.find('a') // still -> 1 (implementations retained) ``` -------------------------------- ### Import all symbols from vitest-mock-extended Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/api-reference/mock.md Shows the import statement for all documented symbols from the package root. ```typescript import { mock, mockDeep, mockFn, mockClear, mockReset, isMockObject, mocked, mockedFn, stub, VitestMockExtended } from 'vitest-mock-extended' ``` -------------------------------- ### MockOpts Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/types.md Interface for options passed to mock creation functions. Allows configuring deep mocking, toJSON behavior, and fallback implementation. ```APIDOC ## MockOpts ### Description Interface for options passed to mock creation functions. Allows configuring deep mocking, toJSON behavior, and fallback implementation. ### Fields - **deep** (boolean) - Optional - Create nested mock proxies for missing properties. Passed by mockDeep. - **useActualToJSON** (boolean) - Optional - When reading the toJSON property, return JSON.stringify(obj) instead of a mock function. - **fallbackMockImplementation** ((...args: any[]) => any) - Optional - Implementation run when no calledWith entry matches. ### Usage - Accepted by mock(mockImplementation, opts). - The deep and fallbackMockImplementation keys are forwarded by mockDeep. ``` -------------------------------- ### Matcher basic usage Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/api-reference/matchers.md Creates a Matcher instance with a predicate that checks for positive integers. Shows asymmetricMatch() returning true for 2 and false for -2, and toString() returning the description. ```ts import { Matcher } from 'vitest-mock-extended' const aPositiveInteger = new Matcher( (actualValue) => Number.isInteger(actualValue) && actualValue > 0, 'aPositiveInteger()' ) aPositiveInteger.asymmetricMatch(2) // -> true aPositiveInteger.asymmetricMatch(-2) // -> false aPositiveInteger.toString() // -> 'aPositiveInteger()' ``` -------------------------------- ### anySymbol() Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/api-reference/matchers.md Matcher factory that matches any symbol. ```APIDOC ## anySymbol() ### Description Matches any symbol value. ### Signature `anySymbol(): MatcherCreator` ### Usage ```ts mock.method.calledWith(anySymbol()).mockReturnValue(x) ``` ### Predicate `(v) => typeof v === 'symbol'` ### Description String `'anySymbol()'` ``` -------------------------------- ### Capturing a payload argument with captor Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/api-reference/matchers.md Example showing how to capture an argument passed to a mocked method. The captor is used with calledWith to match any argument, and after the call the captured value is available via value and values. ```ts import { captor, mock } from 'vitest-mock-extended' interface Notifier { send: (channel: string, payload: { id: number }) => void } const notifier = mock() const payloadCaptor = captor<{ id: number }>() notifier.send.calledWith('email', payloadCaptor).mockImplementation(() => {}) notifier.send('email', { id: 7 }) const capturedPayload = payloadCaptor.value // { id: 7 } console.log(payloadCaptor.values.length) // 1 ``` -------------------------------- ### anyFunction() Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/api-reference/matchers.md Matcher factory that matches any function. ```APIDOC ## anyFunction() ### Description Matches any function value. ### Signature `anyFunction(): MatcherCreator` ### Usage ```ts mock.method.calledWith(anyFunction()).mockReturnValue(x) ``` ### Predicate `(v) => typeof v === 'function'` ### Description String `'anyFunction()'` ``` -------------------------------- ### Deep mocks with fallback mock implementation Source: https://github.com/eratio08/vitest-mock-extended/blob/main/README.md Provide a fallbackMockImplementation to mockDeep to throw an error when no return value is defined with calledWith. The example shows a fallback that throws 'not mocked' and expects the error when calling getNumber. ```TypeScript import { mockDeep } from 'jest-mock-extended'; const mockObj = mockDeep({ fallbackMockImplementation: () => { throw new Error('please add expected return value using calledWith'); }, }); expect(() => mockObj.getNumber()).toThrowError('not mocked'); ``` -------------------------------- ### Deep mocks with mockDeep Source: https://github.com/eratio08/vitest-mock-extended/blob/main/README.md Use mockDeep to create a deep mock proxy that mocks nested objects returned from methods. The example shows mocking a deep property and setting a return value with calledWith, then asserting the call. ```TypeScript import { mockDeep } from 'vitest-mock-extended'; const mockObj: DeepMockProxy = mockDeep(); mockObj.deepProp.getNumber.calledWith(1).mockReturnValue(4); expect(mockObj.deepProp.getNumber(1)).toBe(4); ``` -------------------------------- ### Basic calledWithFn with matchers and literals Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/api-reference/calledwith-fn.md Creates a standalone mock function with calledWithFn, registering return values for argument patterns using anyString, anyNumber, and literals. When multiple entries match, the later registration wins. ```ts import { calledWithFn, anyNumber, anyString } from 'vitest-mock-extended' const fn = calledWithFn() fn.calledWith(anyString(), 1).mockReturnValue(10) fn.calledWith('literal', anyNumber()).mockReturnValue(20) fn('anything', 1) // -> 10 fn('literal', 5) // -> 20 fn('literal', 1) // -> 20 — both entries match ('anyString' + literal 1, // literal + 'anyNumber'), the later registration wins ``` -------------------------------- ### any() Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/api-reference/matchers.md Matcher factory that matches any value. ```APIDOC ## any() ### Description Matches any value. Always returns true. ### Signature `any(): MatcherCreator` ### Usage ```ts mock.method.calledWith(any()).mockReturnValue(x) ``` ### Predicate `() => true` ### Description String `'any()'` ``` -------------------------------- ### anyMap() Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/api-reference/matchers.md Matcher factory that matches any Map instance. ```APIDOC ## anyMap() ### Description Matches any Map instance. ### Signature `anyMap(): MatcherCreator>` ### Usage ```ts mock.method.calledWith(anyMap()).mockReturnValue(x) ``` ### Predicate `(v) => v instanceof Map` ### Description String `'anyMap()'` ``` -------------------------------- ### Clearing and resetting mocks with mockClear and mockReset Source: https://github.com/eratio08/vitest-mock-extended/blob/main/README.md Use mockReset or mockClear in a beforeEach hook to reset or clear mocks between tests, similar to vi.fn(). The example shows importing mock, mockClear, and mockReset from 'vitest-mock-extended' and calling mockReset(mock) (or mockClear(mock)) in beforeEach. ```TypeScript import { mock, mockClear, mockReset } from 'vitest-mock-extended'; describe('test', () => { const mock: UserService = mock(); beforeEach(() => { mockReset(mock); // or mockClear(mock) }); ... }) ``` -------------------------------- ### anyString() Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/api-reference/matchers.md Matcher factory that matches any string value. ```APIDOC ## anyString() ### Description Matches any string value. ### Signature `anyString(): MatcherCreator` ### Usage ```ts mock.method.calledWith(anyString()).mockReturnValue(x) ``` ### Predicate `(v) => typeof v === 'string'` ### Description String `'anyString()'` ``` -------------------------------- ### Catch TypeError from mockFn and guard with vi.isMockFunction Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/errors.md This example shows how to catch the TypeError thrown by mockFn when passing a plain function, and how to guard beforehand using vi.isMockFunction. The try/catch logs the error message 'mockFn expects a Vitest mock function'. The guard comment indicates the recommended approach: verify with vi.isMockFunction before decorating. ```typescript import { mockFn } from 'vitest-mock-extended' const plain = (value: string) => value.length > 0 try { mockFn(plain) } catch (error) { if (error instanceof TypeError) { console.error(error.message) // 'mockFn expects a Vitest mock function' } } // guard beforehand instead if (/* is a real Vitest mock, e.g. produced by vi.fn() */) { const m = mockFn(plain) } ``` -------------------------------- ### anySet() Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/api-reference/matchers.md Matcher factory that matches any Set instance. ```APIDOC ## anySet() ### Description Matches any Set instance. ### Signature `anySet(): MatcherCreator>` ### Usage ```ts mock.method.calledWith(anySet()).mockReturnValue(x) ``` ### Predicate `(v) => v instanceof Set` ### Description String `'anySet()'` ``` -------------------------------- ### mockDeep(opts, mockImplementation?) Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/api-reference/mock.md Creates a deeply mocked proxy for type T. The first overload accepts an options object with funcPropSupport and fallbackMockImplementation, and an optional mockImplementation as the second argument. The second overload accepts only a mockImplementation object. ```APIDOC ## mockDeep(opts, mockImplementation?) ### Description Creates a deeply mocked proxy for type T. The first overload accepts an options object with funcPropSupport and fallbackMockImplementation, and an optional mockImplementation as the second argument. The second overload accepts only a mockImplementation object. ### Method function ### Endpoint mockDeep(opts, mockImplementation?) ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - `opts` (object) - Required - Options object with `funcPropSupport` (boolean, optional) and `fallbackMockImplementation` (function, optional). - `mockImplementation` (DeepPartial) - Optional - Partial implementation of T to preserve real values. ### Request Example ```ts import { mockDeep } from 'vitest-mock-extended' const car = mockDeep({ engine: { hp: 300 } }) ``` ### Response #### Success Response (DeepMockProxy) - Returns a DeepMockProxy that intersects with T. #### Response Example ```ts car.engine.hp // 300 ``` ### Error Handling - No explicit error handling is documented. ``` -------------------------------- ### isA(clazz) Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/api-reference/matchers.md Matcher factory that matches instances of a given class. ```APIDOC ## isA(clazz) ### Description Matches any value that is an instance of the given class. ### Signature `isA(clazz: any): MatcherCreator` ### Usage ```ts mock.method.calledWith(isA(MyClass)).mockReturnValue(x) ``` ### Predicate `(v) => v instanceof clazz` ### Description String `'isA()'` ``` -------------------------------- ### anyObject() Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/api-reference/matchers.md Matcher factory that matches any non-null object. ```APIDOC ## anyObject() ### Description Matches any non-null object. ### Signature `anyObject(): MatcherCreator` ### Usage ```ts mock.method.calledWith(anyObject()).mockReturnValue(x) ``` ### Predicate `(v) => typeof v === 'object' && v !== null` ### Description String `'anyObject()'` ``` -------------------------------- ### Use custom matcher in mock Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/api-reference/matchers.md Shows how to use a custom matcher in a consumer. The mock's emit method is set up to match calls with isIsoDate() and then called with a valid date, which is matched. ```ts // consumer import { mock } from 'vitest-mock-extended' import { isIsoDate } from './custom-matchers' interface Calendar { emit: (date: IsoDate) => void } const calendar = mock() calendar.emit.calledWith(isIsoDate()).mockImplementation(() => {}) calendar.emit({ year: 2026, month: 1, day: 1 }) // matched ``` -------------------------------- ### Usage pattern for matcher factories Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/api-reference/matchers.md Shows the general usage pattern for matcher factories: pass matchers like anyNumber() and isA(MyClass) to calledWith() and chain mockReturnValue(). ```ts mock.method.calledWith(anyNumber(), isA(MyClass)).mockReturnValue(x) ``` -------------------------------- ### mock Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/api-reference/mock.md Creates a mock object of type T with all methods replaced by Vitest mock functions augmented with calledWith. Optionally accepts a partial real implementation and configuration options. ```APIDOC ## mock ### Description Creates a mock object of type T with all methods replaced by Vitest mock functions augmented with calledWith. Optionally accepts a partial real implementation and configuration options. ### Signature ```ts const mock = & T = MockProxy & T>( mockImplementation: DeepPartial = {} as DeepPartial, opts?: MockOpts ): MockedReturn => { mockImplementation!._isMockObject = true return overrideMockImp(mockImplementation, opts) } ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `mockImplementation` | `DeepPartial` | no | `{}` | Partial real implementation to preserve on the mock (property values, real method implementations, nested objects). | | `opts` | `MockOpts` | no | `undefined` | Optional behavior flags; see [configuration.md](../configuration.md). | `MockOpts` (source: `src/Mock.ts:62–67`): | Key | Type | Required | Description | |-----|------|----------|-------------| | `deep` | `boolean` | no | Build nested mock proxies for missing properties instead of plain mock functions. | | `useActualToJSON` | `boolean` | no | Return `JSON.stringify(obj)` when the `toJSON` property is read. | | `fallbackMockImplementation` | `(...args: any[]) => any` | no | Implementation invoked when no `calledWith` entry matches and no other implementation is set. | ### Return type `MockedReturn` — defaults to `MockProxy & T`. Every method of `T` is replaced by `T[K] & CalledWithMock` (source: `src/Mock.ts:36–40`), so every mock method is a Vitest `Mock` augmented with `calledWith`. The created object is flagged with `_isMockObject = true` and is detectable by `isMockObject`. ### Behavior - Each missing property is lazily created as a `calledWith`-decorated `vi.fn()` on first access (`src/Mock.ts:182–189`). - Properties named in the global `ignoreProps` list (default: `['then']`) return `undefined` instead of creating a mock (`src/Mock.ts:166–168`). - Reading `Symbol.iterator` does not create a mock (`src/Mock.ts:170–172`). - A `Date` instance property keeps its real methods bound (`src/Mock.ts:192–196`). ### Examples ```ts import { mock } from 'vitest-mock-extended'; interface PartyProvider { getPartyType: () => string getSongs: (type: string) => string[] start: (type: string) => void } const provider = mock({ getPartyType: () => 'west coast party' }) provider.getPartyType() // -> 'west coast party' (from implementation) provider.getSongs.calledWith('jazz').mockReturnValue(['Take Five']) provider.getSongs('jazz') // -> ['Take Five'] provider.start('disco party') // records the call on a vi.fn() ``` ```ts import { mock } from 'vitest-mock-extended'; interface Client { fetch: (id: number) => string } const client = mock({}, { fallbackMockImplementation: () => { throw new Error('no expectation registered for these args') }, }) client.fetch.calledWith(1).mockReturnValue('one') client.fetch(1) // -> 'one' try { client.fetch(999) // no calledWith entry, fallback throws } catch (error) { console.error((error as Error).message) // 'no expectation registered for these args' } ``` ``` -------------------------------- ### GlobalConfig Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/types.md Configuration object for mock behavior, allowing customization of which properties are ignored when creating mocks. ```APIDOC ## GlobalConfig ### Description Configuration object for mock behavior, allowing customization of which properties are ignored when creating mocks. ### Type Interface ### Fields | Name | Type | Required | Default | Description | |------|------|----------|---------|-------------| | `ignoreProps` | `(string \| number \| symbol)[]` | no | `['then']` | Property names that resolve to `undefined` instead of creating a mock function. Ignoring `'then'` prevents mocks from being mistaken for promises. | ### Usage Accepted by `VitestMockExtended.configure(config: GlobalConfig)`. ``` -------------------------------- ### mockDeep with funcPropSupport Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/configuration.md Demonstrates mockDeep with funcPropSupport: true to mock function members that also carry properties, making both the function and its nested members mockable. ```typescript import { mockDeep } from 'vitest-mock-extended' interface Router { (path: string): string // function that also has properties get: (path: string) => string routes: { root: string } } const router = mockDeep({ funcPropSupport: true }) router.calledWith('/').mockReturnValue('home') router.get.calledWith('/about').mockReturnValue('about') router.routes.root // deep-mocked value ``` -------------------------------- ### Basic matcher usage with anyNumber, anyString, arrayIncludes Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/api-reference/matchers.md Basic usage of anyNumber(), anyString(), and arrayIncludes() matchers with a mocked interface. Shows that anyNumber() matches 0 and arrayIncludes() matches an array containing the given value. ```ts import { anyNumber, anyString, arrayIncludes, mock } from 'vitest-mock-extended' interface Repo { find: (id: number) => string save: (tags: string[]) => void } const repo = mock() repo.find.calledWith(anyNumber()).mockReturnValue('record') repo.find(42) // -> 'record' repo.find(0) // -> 'record' (0 passes anyNumber) repo.save.calledWith(arrayIncludes('urgent')).mockImplementation(() => {}) repo.save(['urgent', 'later']) // matched ``` -------------------------------- ### Import exported types from vitest-mock-extended Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/types.md Import all named types exported from the package entry point. This is the recommended way to bring in the types for use in your test files. ```ts import { type MockProxy, type DeepMockProxy, type CalledWithMock, type MockOpts, type GlobalConfig, type MatcherCreator, type MatcherFn, type MatcherLike, type MatchersOrLiterals, } from 'vitest-mock-extended' ``` -------------------------------- ### mocked Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/api-reference/mock.md Helper function that returns the same value at runtime but types it as a MockProxy (shallow) or DeepMockProxy (deep) for use with mocked modules. ```APIDOC ## `mocked` ### Signatures ```ts function mocked(obj: T, deep?: false): ReturnType> function mocked(obj: T, deep: true): ReturnType> function mocked(obj: T, _deep?: boolean) { return obj } ``` Source: `src/Mock.ts:237–241`. ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `obj` | `T` | yes | — | A value imported from a mocked module. | | `deep` | `boolean` | no | `false` | When `true`, types the result as the return of `mockDeep` instead of `mock`. | ### Return type The same value at runtime (`return obj`); statically typed as `MockProxy` (shallow) or `DeepMockProxy` (deep). Analogous to Vitest's `vi.mocked` for values. ### Example ```ts import { mocked } from 'vitest-mock-extended' import { trader } from './some-module' // in a vi.mock factory (the module is hoisted, so you mock it there): // vi.mock('./some-module', () => ({ trader: mock() })) const traderMock = mocked(trader) // shallow MockProxy flavor const traderDeepMock = mocked(trader, true) // deep DeepMockProxy flavor traderMock.execute.mockReturnValue('ok') ``` ``` -------------------------------- ### mock with useActualToJSON and fallbackMockImplementation Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/configuration.md Shows how to pass MockOpts as the second argument to mock. useActualToJSON makes JSON.stringify(mock) return the mock's contents, while fallbackMockImplementation provides an implementation when no calledWith entry matches. ```typescript import { mock } from 'vitest-mock-extended' interface Payload { test: string; hello: number } // useActualToJSON const m = mock({ test: 'default' }, { useActualToJSON: true }) JSON.stringify(m) // '{"test":"default","_isMockObject":true}' // fallbackMockImplementation const guarded = mock({}, { fallbackMockImplementation: () => { throw new Error('not mocked') }, }) ``` -------------------------------- ### MatcherLike<_> Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/types.md Structural interface for asymmetric matchers, compatible with Vitest's built-in matchers. ```APIDOC ## MatcherLike<_> ### Description Structural interface for asymmetric matchers, compatible with Vitest's built-in matchers. ### Type Interface ### Fields | Field | Type | Required | Description | |-------|------|----------|-------------| | `asymmetricMatch` | `(other: unknown) => boolean` | yes | Matches the actual value. | | `toString` | `() => string` | yes | Matcher description. | | `getExpectedType` | `() => string` | no | Expected type hint. | | `toAsymmetricMatcher` | `() => string` | no | Serialized matcher representation. | ### Usage Element type of `MatchersOrLiterals`. Implemented by `Matcher`. ``` -------------------------------- ### Configure and reset ignoreProps — VitestMockExtended Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/configuration.md Shows how to use VitestMockExtended.configure to allow mocking a 'then' property and resetConfig to restore the default behavior. After configure({ ignoreProps: [] }), the mock's 'then' property can be mocked; after resetConfig, 'then' is ignored again. ```typescript import { VitestMockExtended, mock } from 'vitest-mock-extended' // allow mocking a 'then' property VitestMockExtended.configure({ ignoreProps: [] }) const m = mock<{ then: (cb: () => void) => void }>() m.then.calledWith().mockImplementation((cb) => cb()) VitestMockExtended.resetConfig() const m2 = mock<{ then: (cb: () => void) => void }>() m2.then // undefined — 'then' ignored again ``` -------------------------------- ### mockFn Source: https://github.com/eratio08/vitest-mock-extended/blob/main/_autodocs/api-reference/mock.md Creates a new Vitest mock function or decorates an existing one with calledWith support. Returns the same mock instance with calledWith added, preserving identity. Throws a TypeError if an existingMock is provided but is not a Vitest mock function. ```APIDOC ## mockFn ### Description Creates a new Vitest mock function or decorates an existing one with calledWith support. Returns the same mock instance with calledWith added, preserving identity. Throws a TypeError if an existingMock is provided but is not a Vitest mock function. ### Signature ```ts const mockFn = < T, A extends any[] = T extends (...args: infer AReal) => any ? AReal : any[], R = T extends (...args: any) => infer RReal ? RReal : any, >( existingMock?: T ): CalledWithMock & T => { if (existingMock !== undefined && !vi.isMockFunction(existingMock)) { throw new TypeError('mockFn expects a Vitest mock function') } return calledWithFn({ mock: existingMock as Mock> }) } ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `existingMock` | `T` (a function type) | no | `undefined` | An existing Vitest mock (e.g. from `vi.fn()` or `vi.mock(...)`). When omitted, a new `vi.fn()` is created. `A` and `R` are inferred from `T` when `T` is a function type. | ### Return type `CalledWithMock & T` — the same Vitest mock instance (identity is preserved) augmented with `calledWith`. When an existing mock is passed and it was already decorated, the cached decoration is returned (`decoratedMocks` WeakMap, `src/CalledWithFn.ts:60–65`), so repeated calls return the exact same object. ### Throws | Error type | Condition | |------------|-----------| | `TypeError` | `existingMock` is defined but is not a Vitest mock function (`vi.isMockFunction` is false). Message: `mockFn expects a Vitest mock function` (`src/Mock.ts:221–223`). See [errors.md](../errors.md). | ### Examples ```ts import { mockFn } from 'vitest-mock-extended' type Fetch = (url: string) => Promise const fetch = mockFn() fetch.calledWith('https://example.com/a').mockResolvedValue(200) await fetch('https://example.com/a') // -> 200 await fetch('https://example.com/b') // -> undefined ``` ```ts import { vi } from 'vitest' import { mockFn } from 'vitest-mock-extended' const original = vi.fn((value: string) => value.length > 0) // real Vitest mock const decorated = mockFn(original) decorated.calledWith('blocked').mockReturnValue(false) decorated('blocked') // -> false decorated('fine') // -> true (original implementation kept as fallback) try { mockFn(() => true) // plain function, not a Vitest mock } catch (e) { console.error((e as TypeError).message) // 'mockFn expects a Vitest mock function' } ``` ```