Sinon.js logo

Sinon.js

Open Source

Standalone test spies, stubs, and mocks for JavaScript — works with any test framework.

Visit websiteGitHub

Pricing

Free / Open source

Type

Automation

Languages

JavaScript, TypeScript

// VERDICT

Reach for Sinon.js when you need flexible spies/stubs/mocks (and fake timers) to isolate JS units, with any test runner. Skip it when you only need HTTP mocking (Nock/MSW), your runner's built-ins suffice, or you're not in JS.

Best for

Standalone test spies, stubs and mocks for JavaScript - isolating units by faking functions, methods, timers and behaviour, framework-agnostic across any JS test runner.

Avoid when

You only need HTTP mocking (Nock/MSW), your runner has sufficient built-in mocking, or you're not in JS.

CI/CD fit

Library with any JS runner · spies/stubs/mocks/fake timers

Languages

JavaScript · TypeScript

Team fit

JS/TS teams · Unit testing with isolation · Any test runner

Setup

Easy

Maintenance

Low

Learning

Intermediate

Licence

Free / Open source

// BEST FOR

  • Spies to record how functions are called
  • Stubs to replace behaviour deterministically
  • Mocks with expectations
  • Fake timers to control time in tests
  • Framework-agnostic (works with any runner)
  • Isolating units from their dependencies

// AVOID WHEN

  • You only need HTTP mocking (Nock/MSW)
  • Your runner's built-in mocking suffices
  • You're not in JS
  • Over-mocking would hide real integration issues
  • Minimal dependencies are mandated
  • End-to-end realism is the goal

// QUICK START

npm install -D sinon
// const stub = sinon.stub(obj, 'method').returns(42); sinon.spy(...); clock = sinon.useFakeTimers();

// ALTERNATIVES TO CONSIDER

ToolChoose it when
NockYou specifically need to mock outgoing HTTP.
MSWYou want network-level mocking for the browser/frontend.
Testing LibraryYou want user-centric component tests (with light mocking).

// FEATURES

  • Spies for tracking function calls and arguments
  • Stubs for replacing function behaviour in tests
  • Mocks combining stubs with built-in expectations
  • Fake timers and clock for testing time-dependent code
  • Sandbox API for clean per-test setup and teardown

// PROS

  • Framework-agnostic — works with Mocha, Jest, Vitest, others
  • No dependencies — small footprint
  • Mature and stable, with battle-tested API
  • Strong assertion helpers via sinon-chai integration

// CONS

  • API surface is large — easy to over-mock and obscure intent
  • Overlap with Jest/Vitest built-in mocks on those runners
  • Documentation can lag behind newer features

// EXAMPLE QA WORKFLOW

  1. Install Sinon

  2. Create spies/stubs/mocks in tests

  3. Use fake timers where needed

  4. Assert on interactions

  5. Restore fakes after each test

  6. Avoid over-mocking

// RELATED QA.CODES RESOURCES