Skip to content

Commit

Permalink
feat: add functionality to safe mock functions marchaos#17
Browse files Browse the repository at this point in the history
  • Loading branch information
regevbr committed Mar 29, 2020
1 parent 6179ed2 commit f7c1bdd
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
18 changes: 14 additions & 4 deletions src/Mock.spec.ts
@@ -1,4 +1,4 @@
import mock, { mockClear, mockDeep, mockReset } from './Mock';
import mock, { mockClear, mockDeep, mockReset, mockFn } from './Mock';
import { anyNumber } from './Matchers';
import calledWithFn from './CalledWithFn';

Expand Down Expand Up @@ -107,9 +107,9 @@ describe('jest-mock-extended', () => {

describe('calledWith', () => {
test('can use calledWith without mock', () => {
const mockFn = calledWithFn();
mockFn.calledWith(anyNumber(), anyNumber()).mockReturnValue(3);
expect(mockFn(1, 2)).toBe(3);
const mockFunc = calledWithFn();
mockFunc.calledWith(anyNumber(), anyNumber()).mockReturnValue(3);
expect(mockFunc(1, 2)).toBe(3);
});

test('Can specify matchers', () => {
Expand Down Expand Up @@ -349,4 +349,14 @@ describe('jest-mock-extended', () => {
expect(mockObj.deepProp.getNumber(1)).toBe(4);
});
});

describe('function mock', () => {
test('should mock function', async () => {
type MyFn = (x: number, y: number) => Promise<string>;
const mockFunc = mockFn<MyFn>();
mockFunc.mockResolvedValue(`str`);
const result: string = await mockFunc(1, 2);
expect(result).toBe(`str`);
});
})
});
8 changes: 8 additions & 0 deletions src/Mock.ts
Expand Up @@ -116,4 +116,12 @@ const mock = <T>(mockImplementation: DeepPartial<T> = {} as DeepPartial<T>, opts
return overrideMockImp(mockImplementation, opts);
};

export const mockFn = <T extends Function>(): T extends (...args: infer A) => infer B ? CalledWithMock<B, A> & T : T => {
const mockImplementation = calledWithFn();
// @ts-ignore private
mockImplementation!._isMockFunction = true;
// @ts-ignore
return mockImplementation;
};

export default mock;

0 comments on commit f7c1bdd

Please sign in to comment.