UNPKG

stubfn

Version:

A minimal, zero-dependency stub utility for JavaScript testing. Simple API, predictable behavior, and no magic—perfect for replacing Sinon in modern test setups.

71 lines • 2.4 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.stub = void 0; const node_util_1 = require("node:util"); function format(value) { return (0, node_util_1.inspect)(value, { depth: null, colors: true }); } function stub(name) { let expectedArgs = null; let returnValue = undefined; let whenArgs = []; let calls = []; const fn = (...args) => { calls.push(args); // If the return value is a function, call it with the arguments if (returnValue instanceof Function) { return returnValue(...args); } if (returnValue instanceof Error) { throw returnValue; } // If there are expected arguments, check if the arguments match, otherwise throw an error if (expectedArgs !== null) { const isMatch = (0, node_util_1.isDeepStrictEqual)(expectedArgs, args); if (!isMatch) { throw new Error(`Stub ${name ? `"${name}" ` : ''}called with unexpected arguments.\nExpected: ${format(expectedArgs)}\nReceived: ${format(args)}`); } } // If there are when args, if there are any matches, return the corresponding return value if (whenArgs.length > 0) { const match = whenArgs.find((whenArg) => (0, node_util_1.isDeepStrictEqual)(whenArg.args, args)); if (match) return match.returns; } // Otherwise, return the return value return returnValue; }; fn.getCalls = () => calls; fn.getNumCalls = () => calls.length; fn.expects = (...expected) => { if (whenArgs.length > 0) throw new Error('Cannot use expects() after when()'); expectedArgs = expected; return fn; }; fn.returns = (value) => { returnValue = value; return fn; }; fn.throws = fn.returns; fn.when = (args, returns) => { if (expectedArgs !== null) throw new Error('Cannot use when() after expects()'); whenArgs.push({ args, returns }); return fn; }; fn.clearCalls = () => { calls = []; return fn; }; fn.reset = () => { expectedArgs = null; returnValue = undefined; whenArgs = []; calls = []; return fn; }; return fn; } exports.stub = stub; //# sourceMappingURL=stub.js.map