MediumPro challengePythonJavaScriptTypeScript
Implement jest.fn() Spy
TestingMocking
A spy is a fake function that records every call made to it. Implement one.
solve(ops) receives a list of operations, runs them in order against a fresh set of spies, and returns the list of their results:
| Op | Args | Result |
|---|---|---|
['create', returnValue?] | new spy ID (0, 1, …). Calling the spy returns returnValue, or null if none was given. | |
['call', id, ...args] | the spy's current return value. Records the call. | |
['getCalls', id] | every call so far: [{ args, returnValue }] | |
['getCallCount', id] | number of recorded calls | |
['mockReturnValue', id, value] | null — future calls return value | |
['reset', id] | null — clears the call history, keeps the return value |
solve([
['create', 42],
['call', 0, 'a', 'b'],
['getCalls', 0],
])
// → [0, 42, [{ args: ['a', 'b'], returnValue: 42 }]]Sample tests
Test #1history keeps the value returned at call time
Input: [[["create",1],["call",0,"x"],["mockReturnValue",0,2],["call",0,"y"],["getCalls",0]]]
Output: [0,1,null,2,[{"args":["x"],"returnValue":1},{"args":["y"],"returnValue":2}]]
Test #2create returns the first spy ID
Input: [[["create",42]]]
Output: [0]
Test #3call returns the configured value
Input: [[["create",42],["call",0,"a","b"]]]
Output: [0,42]
Test #4getCallCount after one call
Input: [[["create",42],["call",0,"a","b"],["getCallCount",0]]]
Output: [0,42,1]
Test #5getCalls records args and return value
Input: [[["create",42],["call",0,"a","b"],["getCalls",0]]]
Output: [0,42,[{"args":["a","b"],"returnValue":42}]]
Test #6mockReturnValue changes future calls
Input: [[["create",42],["mockReturnValue",0,99],["call",0]]]
Output: [0,null,99]