Skip to the solution
HardLow-Level DesignAsked in 20247 min read

Build a Minimal jest.fn()-Style Spy/Mock Utility

1.5k views

The problem

Problem, as an interviewer would state it: "Implement a minimal createSpy(implementation) — like jest.fn() — that wraps a function, RECORDS every real call's arguments and return value, and supports mockReturnValue, toHaveBeenCalledWith, and toHaveBeenCalledTimes."

Examples:

Code
const add = createSpy((a, b) => a + b);
add(2, 3);
add.toHaveBeenCalledWith(2, 3); // true

Clarifying questions expected:

  • Should the spy still call the REAL wrapped implementation by default, or only ever track calls without invoking anything?
  • Does mockReturnValue need to override the real implementation entirely, regardless of the arguments the spy is called with?
  • Should call arguments be compared by DEEP equality for toHaveBeenCalledWith, not just reference equality?

Code / implementation expected: Yes — real, direct proof that the spy correctly forwards to a real implementation, records real calls, and correctly answers toHaveBeenCalledWith/Times queries, plus mockReturnValue overriding real behavior.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

7 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: the spy correctly forwards to a real implementation, records real calls, and mockReturnValue correctly overrides regardless of arguments

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 141 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextHard

Virtual DOM element mapper

Continue