Sinon.JS Test Spies, Stubs, and Mocks

21.1.2 · active · verified Sun Apr 19

Sinon.js is a widely used, standalone, and test framework-agnostic JavaScript library providing test spies, stubs, and mocks for robust unit testing. The current stable version is 21.1.2. It maintains a consistent release cadence, frequently publishing updates and bug fixes across major versions. Key differentiators include its non-global pollution approach, ease of integration with any testing framework (like Mocha, Jest, or QUnit), and built-in fakes for browser APIs such as timers (setTimeout, setInterval) and XMLHttpRequest. It is designed to be easy to use and requires minimal setup, allowing developers to isolate and test specific units of code effectively by controlling their dependencies and behavior.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates stubbing an asynchronous dependency's method and verifying its interaction for isolated unit testing.

import sinon from 'sinon';

// Simulate an external API dependency
class ExternalAPI {
  async getData(): Promise<string> {
    // In a real application, this would make an actual network call
    return Promise.resolve('Real Data From Server');
  }
}

// Our code under test that depends on ExternalAPI
class MyService {
  constructor(private api: ExternalAPI) {}

  async processData(): Promise<string> {
    const data = await this.api.getData();
    return data.toUpperCase();
  }
}

async function runExample() {
  const api = new ExternalAPI();
  const service = new MyService(api);

  // Create a stub for the API's getData method
  const getDataStub = sinon.stub(api, 'getData');

  // Configure the stub to return a predictable, mock value
  getDataStub.resolves('Mocked Data');

  // Call the method under test, which now uses the stubbed getData
  const result = await service.processData();

  console.log('Processed Result:', result); // Expected output: MOCKED DATA
  console.log('getData was called once:', getDataStub.calledOnce); // Expected output: true

  // Restore the original method to clean up after the test
  getDataStub.restore();
}

runExample().catch(console.error);

view raw JSON →