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
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
170 Stars
623 Commits
7 Forks
1 Branches
1 Contributors
Updated on 27 Nov 2024
Minified
Minified + Gzipped
TypeScript (96.3%)
JavaScript (3.7%)
Cumulative downloads
Total Downloads
Last day
4.2%
45,397
Compared to previous day
Last week
4.5%
224,441
Compared to previous week
Last month
12%
916,700
Compared to previous month
Last year
173.4%
7,274,754
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);
Can can provide a fallback mock implementation 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');
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.