Gathering detailed insights and metrics for vitest-mock-extended
Gathering detailed insights and metrics for vitest-mock-extended
Gathering detailed insights and metrics for vitest-mock-extended
Gathering detailed insights and metrics for vitest-mock-extended
npm install vitest-mock-extended
Typescript
Module System
Node Version
NPM Version
TypeScript (96.44%)
JavaScript (3.56%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
216 Stars
787 Commits
7 Forks
2 Branches
1 Contributors
Updated on Jul 16, 2025
Latest Version
3.1.0
Package Id
vitest-mock-extended@3.1.0
Unpacked Size
117.52 kB
Size
16.62 kB
File Count
11
NPM Version
10.9.2
Node Version
22.14.0
Published on
Apr 04, 2025
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
1
2
Type safe mocking extensions for Vitest ✅
THIS IS A FORK OF jest-mock-extended ALL CREDITS GO TO THE ORIGINAL AUTHOR
1npm install vitest-mock-extended --save-dev
or
1yarn add vitest-mock-extended --dev
If ReferenceError: vi is not defined
related error occurs, please set globals: true
.
1import { mock } from 'vitest-mock-extended'; 2 3interface PartyProvider { 4 getPartyType: () => string; 5 getSongs: (type: string) => string[]; 6 start: (type: string) => void; 7} 8 9describe('Party Tests', () => { 10 test('Mock out an interface', () => { 11 const mock = mock<PartyProvider>(); 12 mock.start('disco party'); 13 14 expect(mock.start).toHaveBeenCalledWith('disco party'); 15 }); 16 17 test('mock out a return type', () => { 18 const mock = mock<PartyProvider>(); 19 mock.getPartyType.mockReturnValue('west coast party'); 20 21 expect(mock.getPartyType()).toBe('west coast party'); 22 }); 23 24 test('Can specify fallbackMockImplementation', () => { 25 const mockObj = mock<MockInt>( 26 {}, 27 { 28 fallbackMockImplementation: () => { 29 throw new Error('not mocked'); 30 }, 31 } 32 ); 33 34 expect(() => mockObj.getSomethingWithArgs(1, 2)).toThrowError('not mocked'); 35 }); 36});
If you wish to assign a mock to a variable that requires a type in your test, then you should use the MockProxy<> type given that this will provide the apis for calledWith() and other built-in vitest types for providing test functionality.
1import { MockProxy, mock } from 'vitest-mock-extended'; 2 3describe('test', () => { 4 let myMock: MockProxy<MyInterface>; 5 6 beforeEach(() => { 7 myMock = mock<MyInterface>(); 8 }) 9 10 test(() => { 11 myMock.calledWith(1).mockReturnValue(2); 12 ... 13 }) 14}); 15
vitest-mock-extended
allows for invocation matching expectations. Types of arguments, even when using matchers are type checked.
1const provider = mock<PartyProvider>(); 2provider.getSongs.calledWith('disco party').mockReturnValue(['Dance the night away', 'Stayin Alive']); 3expect(provider.getSongs('disco party')).toEqual(['Dance the night away', 'Stayin Alive']); 4 5// Matchers 6provider.getSongs.calledWith(any()).mockReturnValue(['Saw her standing there']); 7provider.getSongs.calledWith(anyString()).mockReturnValue(['Saw her standing there']);
You can also use mockFn()
to create a vi.fn()
with the calledWith extension:
1type MyFn = (x: number, y: number) => Promise<string>;
2const fn = mockFn<MyFn>();
3fn.calledWith(1, 2).mockReturnValue('str');
vitest-mock-extended
exposes a mockClear and mockReset for resetting or clearing mocks with the same
functionality as vi.fn()
.
1import { mock, mockClear, mockReset } from 'vitest-mock-extended'; 2 3describe('test', () => { 4 const mock: UserService = mock<UserService>(); 5 6 beforeEach(() => { 7 mockReset(mock); // or mockClear(mock) 8 }); 9 ... 10})
If your class has objects returns from methods that you would also like to mock, you can use mockDeep
in
replacement for mock.
1import { mockDeep } from 'vitest-mock-extended'; 2 3const mockObj: DeepMockProxy<Test1> = mockDeep<Test1>(); 4mockObj.deepProp.getNumber.calledWith(1).mockReturnValue(4); 5expect(mockObj.deepProp.getNumber(1)).toBe(4);
if you also need support for properties on functions, you can pass in an option to enable this
1import { mockDeep } from 'vitest-mock-extended'; 2const mockObj: DeepMockProxy<Test1> = mockDeep<Test1>({ funcPropSupport: true }); 3mockObj.deepProp.calledWith(1).mockReturnValue(3); 4mockObj.deepProp.getNumber.calledWith(1).mockReturnValue(4); 5expect(mockObj.deepProp(1)).toBe(3); 6expect(mockObj.deepProp.getNumber(1)).toBe(4);
You can also provide a fallback mock implementation to be used if you do not define a return value using calledWith
.
1import { mockDeep } from 'jest-mock-extended';
2const mockObj = mockDeep<Test1>({
3 fallbackMockImplementation: () => {
4 throw new Error('please add expected return value using calledWith');
5 },
6});
7expect(() => mockObj.getNumber()).toThrowError('not mocked');
If you mock objects/functions of modules and can't refer them directly due to hoist,
mocked type helpers can be used. This is similar to the use case of Vitest's vi.mocked
1// APIs 2import { mocked, mockedFn } from "vitest-mock-extended"; 3import { originalObj, originalFn} from "somewhere"; 4 5const mockedObj = mocked(originalObj); 6const deepMockedObj = mocked(originalObj, true); 7const mockedFunction = mockedFn(originalFn);
An example would be
1// Mock a module 2// @/libs/example.mock.ts 3import { mock } from "vitest-mock-extended"; 4import { ExampleClient } from "@/libs/example"; 5 6vi.mock(import("@/libs/example"), async (importOriginal) => { 7 const actual = await importOriginal(); 8 return { 9 ...actual, 10 // Due to vi.mock being hoisted, we have to mock here directly instead of 11 // defining an exampleMock outside and assign it to example 12 example: mock<ExampleClient>(), 13 }; 14}); 15 16// Use the mocked object 17import "@/libs/example.mock"; // Mock out the actual client 18import { mocked } from "vitest-mock-extended"; 19import { example } from "@/libs/example"; 20 21const exampleMock = mocked(example); 22 23test("send notification", () => { 24 example.function.mockResolvedValue(xxx); 25 ... 26}
Matcher | Description |
---|---|
any() | Matches any arg of any type. |
anyBoolean() | Matches any boolean (true or false) |
anyString() | Matches any string including empty string |
anyNumber() | Matches any number that is not NaN |
anyFunction() | Matches any function |
anyObject() | Matches any object (typeof m === 'object') and is not null |
anyArray() | Matches any array |
anyMap() | Matches any Map |
anySet() | Matches any Set |
isA(class) | e.g isA(DiscoPartyProvider) |
includes('value') | Checks if value is in the argument array |
containsKey('key') | Checks if the key exists in the object |
containsValue('value') | Checks if the value exists in an object |
has('value') | checks if the value exists in a Set |
notNull() | value !== null |
notUndefined() | value !== undefined |
notEmpty() | value !== undefined && value !== null && value !== '' |
captor() | Used to capture an arg - alternative to mock.calls[0][0] |
Custom matchers can be written using a MatcherCreator
1import { MatcherCreator, Matcher } from 'vitest-mock-extended'; 2 3// expectedValue is optional 4export const myMatcher: MatcherCreator<MyType> = (expectedValue) => 5 new Matcher((actualValue) => { 6 return expectedValue === actualValue && actualValue.isSpecial; 7 });
By default, the expected value and actual value are the same type. In the case where you need to type the expected value differently than the actual value, you can use the optional 2 generic parameter:
1import { MatcherCreator, Matcher } from 'vitest-mock-extended'; 2 3// expectedValue is optional 4export const myMatcher: MatcherCreator<string[], string> = (expectedValue) => 5 new Matcher((actualValue) => { 6 return actualValue.includes(expectedValue); 7 });
No vulnerabilities found.
No security vulnerabilities found.