Skip to content

Instantly share code, notes, and snippets.

@ukslim
Created February 26, 2025 14:30
Show Gist options
  • Save ukslim/fee07e3ab9e976d3d0c3f7c7f8581a52 to your computer and use it in GitHub Desktop.
Save ukslim/fee07e3ab9e976d3d0c3f7c7f8581a52 to your computer and use it in GitHub Desktop.
Testing a functional parameter two ways

Two ways of creating and asserting with a test double for a functional parameter

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);
};

Test double using an ordinary function

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

Test double using jest.fn()

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment