@chubbyts/chubbyts-function-mock
v1.4.3
Published
A function mock helper.
Downloads
520
Readme
chubbyts-function-mock
Description
A function mock helper.
IMPORTANT: deepStrictEqual
is used for parameter comparsion, ===
if you pass strict: true
Requirements
- node: 16
Installation
Through NPM as @chubbyts/chubbyts-function-mock.
npm i @chubbyts/[email protected]
Usage
createFunctionMock
import { expect, test } from '@jest/globals'; // or 'vitest'
import { useFunctionMock } from '@chubbyts/chubbyts-function-mock/dist/function-mock';
type MyFunction = (string: string, start: number, stop: number) => string;
test('my random test', () => {
const [myFunction, myFunctionMocks] = useFunctionMock<MyFunction>([
{ parameters: ['test', 0, 2], return: 'te' },
{
callback: (string: string, start: number, stop: number): string => {
expect(string).toBe('test');
expect(start).toBe(1);
expect(stop).toBe(2);
return 'es';
}
},
{ parameters: ['test', 0, 2], error: new Error('test') },
]);
expect(myFunction('test', 0, 2)).toBe('te');
expect(myFunction('test', 1, 2)).toBe('es');
try {
expect(myFunction('test', 2, 2)).toBe('st');
throw new Error('Expect fail');
} catch (e) {
expect(e).toMatchInlineSnapshot('[Error: test]');
}
// if you want to be sure, that all mocks are called
expect(myFunctionMocks.length).toBe(0);
});
createObjectMock
IMPORTANT: Do not use with spread operator ...myObject
!.
import { expect, test } from '@jest/globals'; // or 'vitest'
import { useObjectMock } from '@chubbyts/chubbyts-function-mock/dist/object-mock';
type MyType = {
substring: (string: string, start: number, stop: number) => string;
uppercase: (string: string) => string;
};
test('my random test', () => {
const [myObject, myObjectMocks] = useObjectMock<MyType>([
{ name: 'substring', parameters: ['test', 0, 2], return: 'te' },
{
name: 'substring',
callback: (string: string, start: number, stop: number): string => {
expect(string).toBe('test');
expect(start).toBe(1);
expect(stop).toBe(2);
return 'es';
}
},
{ name: 'uppercase', parameters: ['test'], error: new Error('test') },
]);
expect(myObject.substring('test', 0, 2)).toBe('te');
expect(myObject.substring('test', 1, 2)).toBe('es');
try {
expect(myObject.uppercase('test')).toBe('st');
throw new Error('Expect fail');
} catch (e) {
expect(e).toMatchInlineSnapshot('[Error: test]');
}
// if you want to be sure, that all mocks are called
expect(myObjectMocks.length).toBe(0);
});
Copyright
2024 Dominik Zogg