Skip to content

Commit

Permalink
bug: mockReset doesn't work well with calledWith marchaos#22
Browse files Browse the repository at this point in the history
  • Loading branch information
regevbr committed Mar 31, 2020
1 parent 6179ed2 commit ff44250
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 4 deletions.
8 changes: 4 additions & 4 deletions src/CalledWithFn.ts
Expand Up @@ -19,19 +19,19 @@ const checkCalledWith = <T, Y extends any[]>(calledWithStack: CalledWithStackIte

export const calledWithFn = <T, Y extends any[]>(): CalledWithMock<T, Y> => {
const fn: jest.Mock<T, Y> = jest.fn();
const calledWithStack: CalledWithStackItem<T, Y>[] = [];
let hasImplementation = false;
let calledWithStack: CalledWithStackItem<T, Y>[] = [];

(fn as CalledWithMock<T, Y>).calledWith = (...args) => {
// We create new function to delegate any interactions (mockReturnValue etc.) to for this set of args.
// If that set of args is matched, we just call that jest.fn() for the result.
const calledWithFn = jest.fn();
if (!hasImplementation) {
// @ts-ignore no type for it, see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/43531
if (!fn.getMockImplementation()) {
// Our original function gets a mock implementation which handles the matching
fn.mockImplementation((...args: Y) => checkCalledWith(calledWithStack, args));
calledWithStack = [];
}
calledWithStack.push({ args, calledWithFn });
hasImplementation = true;

return calledWithFn;
};
Expand Down
2 changes: 2 additions & 0 deletions src/Mock.spec.ts
Expand Up @@ -317,6 +317,8 @@ describe('jest-mock-extended', () => {
expect(mockObj.getSomethingWithArgs(1, 2)).toBe(3);
mockReset(mockObj);
expect(mockObj.getSomethingWithArgs(1, 2)).toBe(undefined);
mockObj.getSomethingWithArgs.calledWith(1, anyNumber()).mockReturnValue(3);
expect(mockObj.getSomethingWithArgs(1, 2)).toBe(3);
});

it('mockClear object', () => {
Expand Down

0 comments on commit ff44250

Please sign in to comment.