QuickDevGuide

Home › Mocha JS Testing

Spies, Stubs & Fake Timers with Sinon — Mocha JS Testing

Sinon (npm i -D sinon) isolates the unit under test from its collaborators. Tool Purpose Example spy records calls, keeps behaviour sinon.spy(obj, "method") stub replaces behaviour .returns(42), .resolves(data), .rejects(err), .throws() fake standalone spy/stub function sinon.fake.resolves({}) fake timers control setTimeout, Date sinon.useFakeTimers() + clock.tick(ms) sandbox restore everything at once sinon.restore() in afterEach Assertions on calls stub.calledOnce, stub.calledWith("a"), stub.firstCall.args, stub.callCount, or sinon.assert.calledWithExactly(stub, ...) for helpful failure messages. Always restore stubs after each test so they don't leak into others.

Key Takeaways