Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Mock Test with jest.spyOn sugar
import * as app from "./app";
import * as math from "./math";
test("calls math.add", () => {
// store the original implementation
const originalAdd = math.add;
// mock add with the original implementation
math.add = jest.fn(originalAdd);
// spy the calls to add
expect(app.doAdd(1, 2)).toEqual(3);
expect(math.add).toHaveBeenCalledWith(1, 2);
// override the implementation
math.add.mockImplementation(() => "mock");
expect(app.doAdd(1, 2)).toEqual("mock");
expect(math.add).toHaveBeenCalledWith(1, 2);
// restore the original implementation
math.add = originalAdd;
expect(app.doAdd(1, 2)).toEqual(3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment