AniUI Academy
medium+250 XPPractice

Build a spy that records its calls

When you assert that a component called onSelect with the right row, you are using a spy. It is a wrapper that passes everything through and keeps a log on the side, and it is about fifteen lines of closure.

Implement createSpy(fn). It returns a spy function that forwards its arguments to fn and returns fn's return value, while recording: spy.calls, an array holding one array of arguments per call, in call order; spy.results, an array of the values returned by each call, in the same order; and spy.callCount, the number of calls. All three start empty or at zero. spy.reset() clears calls and results back to empty arrays and callCount back to 0. createSpy() may also be called with no function at all, in which case the spy records calls as usual and returns undefined.

What it has to do

  • spy.calls holds one array of arguments per call, in order.
  • spy.results holds each call's return value, in order.
  • spy.callCount matches the number of calls, and the spy returns fn's value.
  • spy.reset() empties calls and results and zeroes callCount.
  • With no function to wrap, the spy still records and returns undefined.

Your workspace

Try it yourself
Loading playground...

Ready to check it?

5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.

AI Crack & Solution Assist

Stuck? Get instant AI hints or break down the optimal solution.

Stuck? The javascript course covers everything this challenge needs.