MediumJavaScriptTypeScript

Implement jest.fn() Spy

TestingJavaScriptMocking

Implement solve(op, ...args) that simulates jest.fn():

OpArgsReturns
'create'(returnValue?)spy ID (integer). Creates a new spy that returns returnValue when called. If omitted, returns undefined.
'call'(id, ...callArgs)The spy's configured return value. Records the call.
'getCalls'(id)Array of all calls: [{ args: [...], returnValue }]
'getCallCount'(id)Number of times the spy was called.
'mockReturnValue'(id, value)Updates the return value for future calls. Returns undefined.
'reset'(id)Clears call history. Returns undefined.

Spies are stored in module-level state (the judge runs all test cases in one execution).

const id = solve('create', 42)   // creates spy returning 42
solve('call', id, 'a', 'b')      // calls spy with args ['a','b'], returns 42
solve('getCallCount', id)        // 1
solve('getCalls', id)
// [{ args: ['a', 'b'], returnValue: 42 }]
solve('mockReturnValue', id, 99)
solve('call', id)                // returns 99
solve('reset', id)
solve('getCallCount', id)        // 0

Sample tests

Test #1create returns first spy ID (0)
Input: ["create",42]
Output: 0
Test #2call returns configured return value
Input: ["call",0,"a","b"]
Output: 42
Test #3getCallCount after one call
Input: ["getCallCount",0]
Output: 1
Test #4getCalls records args and return value
Input: ["getCalls",0]
Output: [{"args":["a","b"],"returnValue":42}]
Test #5mockReturnValue returns undefined (null in JSON)
Input: ["mockReturnValue",0,99]
Output: null
Test #6call after mockReturnValue uses new value
Input: ["call",0]
Output: 99