Sinon Cheatsheet - Test Doubles
This reference is for JavaScript developers writing unit tests who need to isolate the code under test from its surroundings. It covers spies for observing calls, stubs to replace behavior with return/throw/resolve constants, strict mocks with expectations, fake timers to fast-forward setTimeout, and sandboxes that auto-restore everything. Later sections show the sinon.assert helpers and practical patterns like sinon.replace and parameter matchers. After reading you should be able to spy on a dependency, stub an external call, control time in tests, and clean up all doubles in a teardown.
Spy 8
sinon.spy(obj, "method")sinon.spy(fn)spy.calledOncespy.calledWith(arg1, arg2)spy.returned(value)spy.callCountspy.args[0]spy.restore()Stub 9
sinon.stub(obj, "method")stub.returns(value)stub.throws(Error)stub.callsFake(fn)stub.resolves(value)stub.rejects(Error)stub.callsArg(0)stub.onCall(0).returns(value)stub.restore()Mock 7
sinon.mock(obj)mock.expects("method")expects.once()expects.withArgs(arg)expects.never()mock.verify()mock.restore()Fake Timers 6
sinon.useFakeTimers()clock.tick(1000)clock.runAll()clock.restore()sinon.useFakeTimers({ now: 1000 })sinon.useFakeTimers({ toFake: ["setTimeout", "Date"] })Assertions & Verification 6
sinon.assert.called(spy)sinon.assert.calledOnce(spy)sinon.assert.calledWith(spy, arg)sinon.assert.notCalled(spy)sinon.assert.callCount(spy, 3)sinon.assert.calledWithExactly(spy, arg)Sandbox 5
sinon.createSandbox()sandbox.spy(obj, "method")sandbox.stub(obj, "method")sandbox.useFakeTimers()sandbox.restore()Useful Patterns 5
sinon.replace(obj, "method", fn)sinon.replaceGetter(obj, "prop", fn)sinon.replaceSetter(obj, "prop", fn)sinon.fake()sinon.match({ id: sinon.match.number })Tips
- Spy watches calls without changing behavior; Stub replaces behavior; Mock combines both and verifies expectations.
- Always restore() after tests, or use a sandbox to manage automatically (call sandbox.restore in afterEach).
- Fake Timers test scheduled tasks without real waits; remember to restore after tick.
- sinon.assert throws errors, suited for test frameworks; you can also read spy properties directly.
- stub.resolves/rejects handle Promises more concisely than callsFake-wrapped async functions.
Official References
Each command links to its official documentation below, so you can verify the latest usage and read deeper.
Maintained by LaoHand
Publicly updated on Jul 21, 2026, continuously proofread against official docs.
Contact Us
Wrong command or description? Send us corrections, business inquiries or product feedback by email.
Contact Us