1.5.2 • Published 10 months ago
@chubbyts/chubbyts-function-mock v1.5.2
chubbyts-function-mock
Description
A function mock helper.
IMPORTANT: deepStrictEqual is used for parameter comparsion, === if you pass strict: true
Requirements
- node: 18
Installation
Through NPM as @chubbyts/chubbyts-function-mock.
npm i @chubbyts/chubbyts-function-mock@1.5.2Usage
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
2025 Dominik Zogg
1.5.2
10 months ago
1.5.1
10 months ago
1.5.0
10 months ago
2.0.0
10 months ago
1.4.3
1 year ago
1.4.2
1 year ago
1.3.6
2 years ago
1.4.1
2 years ago
1.4.0
2 years ago
1.3.5
2 years ago
1.3.4
2 years ago
1.3.3
3 years ago
1.2.6
3 years ago
1.2.5
3 years ago
1.2.4
3 years ago
1.3.2
3 years ago
1.2.3
3 years ago
1.3.1
3 years ago
1.3.0
3 years ago
1.2.2
3 years ago
1.2.1
3 years ago
1.2.0
3 years ago
1.1.0
3 years ago
1.0.0
3 years ago