AniUI Academy
hard+350 XPPractice

Spy on an existing object method

This is what jest.spyOn does. You replace a method on an object you do not own, record what it is called with while letting it behave exactly as before, and restore it when the test ends so nothing leaks into the next one. The this handling is where naive attempts break: the replacement is called as a method, so it must forward that receiver to the original or the original loses access to the object's own state.

Implement spyOn(object, methodName). It replaces object[methodName] with a wrapper that records the call and then invokes the original method with the same this and arguments, returning the original's result unchanged. It returns a spy handle with calls, an array holding one array of arguments per recorded call in order; callCount, the number of recorded calls, starting at 0; and restore(), which puts the original function back so that object[methodName] is once again the exact same function reference it was before, after which calls are no longer recorded. Spying on two different methods of the same object gives two independent handles.

What it has to do

  • The wrapper returns the original method's result, so behaviour is unchanged.
  • Invoke the original with the object as this, so methods using this still work.
  • Record one array of arguments per call in calls, and keep callCount in step.
  • restore() puts back the identical original function reference.
  • Calls made after restore() are not recorded, and two spies on one object stay independent.

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.