Skip to content

Commit

Permalink
allow overriding calledWithFn
Browse files Browse the repository at this point in the history
By using `unshift` instead of `push`, new callbacks are added to the "top" of the stack (since `find` searches from the beginning of the array). This allow a second call to `calledWith()` to override a previous call. This is useful for one-off tests.

Fixes #77.
  • Loading branch information
dlech committed Aug 3, 2022
1 parent e98bc1e commit df31ed3
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/CalledWithFn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export const calledWithFn = <T, Y extends any[]>(): CalledWithMock<T, Y> => {
fn.mockImplementation((...args: Y) => checkCalledWith(calledWithStack, args));
calledWithStack = [];
}
calledWithStack.push({ args, calledWithFn });
calledWithStack.unshift({ args, calledWithFn });

return calledWithFn;
};
Expand Down
8 changes: 8 additions & 0 deletions src/Mock.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,14 @@ describe('jest-mock-extended', () => {
expect(mockObj.getSomethingWithArgs(7, 2)).toBe(undefined);
});

test('supports overriding with same args', () => {
const mockObj = mock<MockInt>();
mockObj.getSomethingWithArgs.calledWith(1, 2).mockReturnValue(4);
mockObj.getSomethingWithArgs.calledWith(1, 2).mockReturnValue(3);

expect(mockObj.getSomethingWithArgs(1, 2)).toBe(3);
})

test('Support jest matcher', () => {
const mockObj = mock<MockInt>();
mockObj.getSomethingWithArgs.calledWith(expect.anything(), expect.anything()).mockReturnValue(3);
Expand Down

0 comments on commit df31ed3

Please sign in to comment.