docs/concepts/spies/error-handling.md
Spies validate their usage and throw errors when used incorrectly. Understanding these errors helps you use spies properly.
Spies cannot be created on ES Modules because their exports are read-only.
import * as myModule from "./my-module.js";
// This will throw: "ES Modules cannot be spied"
sinon.spy(myModule);
Solution: Use individual exports or CommonJS modules if you need to spy on module exports.
Methods like yield(), yieldOn(), yieldTo(), and yieldToOn() can only be called after the spy has been invoked at least once.
const spy = sinon.spy();
// This will throw: "spy cannot yield since it was not yet invoked"
spy.yield();
Solution: Call the spy first, then use yield methods on the call object:
const spy = sinon.spy();
function callback(value) {
/* ... */
}
spy(callback);
spy.getCall(0).yield("value"); // Works!
Methods like callArg(), callArgWith(), callArgOn(), and callArgOnWith() require the spy to have been called first.
const spy = sinon.spy();
// This will throw: "spy cannot call arg since it was not yet invoked"
spy.callArg(0);
Solution: Call the spy first, then use callArg methods on the call object:
const spy = sinon.spy();
function callback() {
/* ... */
}
spy(callback);
spy.getCall(0).callArg(0); // Works!
spy.called or spy.callCount before accessing spy.getCall(n)spy.restore() to clean upsinon.fake() provides a simpler API with the same functionality