We are testing a function that takes a function as an argument. We don't need Jest to do its magic poke-in-replacements-for-imports magic. But we have the option of using jest.fn() to create a test double.
Example is in plain JS so that types don't clutter things.
Code under test (CUT):
const addOneAndApply = (a, fn) => {
const oneAdded = a + 1;
return fn(oneAdded);
};
const fn = (n) => {
expect(n).toBe(4); // A: Is the test double called with expected parameter?
return 12345; // B: What does the test double return?
};
const actual = addOneAndApply(3, fn); // C: Run the CUT
expect(actual).toBe(12345); // D: Does the code under test return the expected value
- requires only standard JS knowledge
- you could give it real functionality
return n * 2
(but see also Jest.mockImplementation()
) - test terminates as soon as this test double fails an
expect
- test double's response and expectations are both defined before the CUT is called
const fn = jest.fn();
fn.mockReturnValue(12345); // B: What does the test double return?
const actual = addOneAndApply(3, fn); // C: Run the CUT
expect(fn).toHaveBeenCalledWith(4); // A: Is the test double called with expected parameter?
expect(actual).toBe(12345); // D: Does the code under test return the expected value
- requires knowledge of the Jest API
- test continues when unexpected parameters are supplied to
fn()
-- only fails when.toHaveBeenCalledWith()
verifies later - test double's response is defined before CUT is run, but expectations are defined after.