This content originally appeared on DEV Community and was authored by Bukunmi Odugbesan
The task is to implement a spyOn function that works just like the jest.spyOn function.
The boilerplate code:
function spyOn(obj, methodName) {
// your code here
}
jest.spyOn wraps an existing method on an object, to track how many times it is called, the arguments it is called with, and what it returns.
If the object doesn't exist, or its property isn't a function, it stops immediately
if (!obj || typeof obj[methodName] !== "function") {
throw new Error("Can't spy on a non-function property");
}
Save the original method
const originalMethod = obj[methodName]
A spy object is created, which keeps all spy data and helper methods.
const spy = {
calls: [],
callCount: 0,
restore() {
obj[methodName] = originalMethod;
}
};
Replace the original method, record the call data, and then call the original function. Record the return value.
obj[methodName] = function (...args) {
spy.callCount++;
spy.calls.push(args);
const result = originalMethod.apply(this, args);
spy.lastReturn = result;
return result;
Return the original result.
return result
The final code
function spyOn(obj, methodName) {
// your code here
if(!obj || typeof obj[methodName] !== "function") {
throw new Error("Can't spy on a non-function property")
}
const originalMethod = obj[methodName];
const spy = {
calls: [],
callCount: 0,
restore() {
obj[methodName] = originalMethod;
}
};
obj[methodName] = function(...args) {
spy.callCount++;
spy.calls.push(args);
const result = originalMethod.apply(this, args);
spy.lastReturn = result;
return result;
}
return spy;
}
That's all folks!
This content originally appeared on DEV Community and was authored by Bukunmi Odugbesan
Bukunmi Odugbesan | Sciencx (2025-10-28T20:46:39+00:00) Coding Challenge Practice – Question 39. Retrieved from https://www.scien.cx/2025/10/28/coding-challenge-practice-question-39/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.