API Reference

Sinon.JS

Standalone test spies, stubs and mocks for JavaScript, plus fake timers and sandboxed test isolation.

Official Documentation ↗
CompatibilityThis documentation covers version v22.1.0. Check the official docs for the latest API surface.

Installation

npmnpm install sinon
pnpmpnpm add sinon
yarnyarn add sinon

Methods

Overview

Sinon provides spies, stubs, mocks and fake timers for JavaScript tests. It isolates the unit under test by replacing collaborators and controlling time.

Core Methods

sinon.spy records calls, sinon.stub replaces behavior with controllable returns or errors, and sinon.useFakeTimers controls clock advancement. Sandboxes group fakes for one-command cleanup.

Usage Notes

Wrap fakes in a sandbox and restore in afterEach so tests do not leak state. Stub at the boundary of the unit under test, not deep internals, to keep tests meaningful.

Common Pitfalls

Stubbing too much couples tests to implementation and lets real bugs pass. Forgetting restore pollutes later tests. Faking time without restoring can break unrelated suites.

FAQ

What is the difference between a spy and a stub?
A spy records calls but keeps the original implementation. A stub replaces it, so you control the return value and can force errors, making stubs better for isolating the unit under test.
How do I clean up after tests?
Use sinon.createSandbox and call sandbox.restore in afterEach, or call restore on each fake. Leaving stubs installed leaks state into later tests.
Can sinon fake Date?
Yes. useFakeTimers can also replace Date, so time-dependent code such as token expiry can be tested at precise instants without real waiting.