Spy And Stub Test Recorder
A tiny dependency-free spy that records calls, supports return stubs and resolved values, and resets between tests.
Code
export function createSpy(implementation = () => undefined) {
if (typeof implementation !== "function") {
throw new TypeError("implementation must be a function");
}
let behavior = implementation;
const calls = [];
const spy = function spyWrapper(...args) {
const call = { args, thisArg: this, result: undefined, error: undefined };
calls.push(call);
try {
call.result = behavior.apply(this, args);
return call.result;
} catch (error) {
call.error = error;
throw error;
}
};
spy.calls = calls;
spy.callCount = () => calls.length;
spy.calledWith = (...expected) => calls.some((call) => {
return expected.every((value, index) => Object.is(value, call.args[index]));
});
spy.mockImplementation = (next) => {
if (typeof next !== "function") throw new TypeError("next must be a function");
behavior = next;
return spy;
};
spy.mockReturnValue = (value) => {
behavior = () => value;
return spy;
};
spy.mockResolvedValue = (value) => {
behavior = () => Promise.resolve(value);
return spy;
};
spy.reset = () => {
calls.length = 0;
behavior = implementation;
return spy;
};
return spy;
}How the snippet works
Spy And Stub Test Recorder reduces to the functions createSpy and spyWrapper.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. The failure path is explicit — TypeError is raised when the guard condition holds.
Points of care
- The guard
typeof implementation !== "function"short-circuits the flow with an earlythrowwhen its condition holds.
Using it
The main signature reads export function createSpy(implementation = ()
Callers only need createSpy — everything else stays internal.
Key statements
return expected.every((value, index) => Object.is(value, call.args[index]));
behavior = () => Promise.resolve(value);
if (typeof next !== "function") throw new TypeError("next must be a function");
Interactive Tools for This Topic
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does the code validate its input?
- The code throws `TypeError` — the guard `typeof implementation !== "function"` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
- What has to be installed first?
- Nothing — the runtime itself provides everything the code touches. The file defines `createSpy`, `spyWrapper` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.