Sinon-Chai: Sinon.JS Assertions for Chai

4.0.1 · active · verified Sun Apr 19

Sinon-Chai is a testing utility that integrates the Sinon.JS mocking framework with the Chai assertion library, allowing developers to write more expressive and readable assertions for spies, stubs, and mocks. Instead of using Sinon's direct assertion methods (`sinon.assert.calledWith`) or awkward Chai property checks, Sinon-Chai extends Chai's `should` and `expect` interfaces to provide natural language assertions like `expect(mySpy).to.have.been.calledWith('foo')`. The current stable version is 4.0.1, which supports Chai v5 and v6, and Sinon v4+. The library maintains an active release cadence, typically updating to support new major versions of its peer dependencies, Chai and Sinon. Key differentiators include its seamless integration into the Chai assertion chain, improving test readability and developer experience by providing a unified assertion style across a test suite. It's widely used in JavaScript testing environments for both Node.js and browser applications.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up Sinon-Chai with Chai and Sinon, creating a spy and using `expect` assertions to verify call counts and arguments.

import { expect, use } from 'chai';
import * as sinon from 'sinon';
import sinonChai from 'sinon-chai';

// Initialize Chai with sinon-chai plugin
use(sinonChai);

describe('MyService with Sinon-Chai', () => {
  let mySpy: sinon.SinonSpy;

  beforeEach(() => {
    // Create a new Sinon spy before each test
    mySpy = sinon.spy();
  });

  afterEach(() => {
    // Restore the spy after each test to prevent side effects
    mySpy.restore();
  });

  it('should call the spy once with the expected argument', () => {
    const serviceMethod = (param: string) => {
      mySpy(param);
    };

    serviceMethod('first-call');

    // Use sinon-chai assertions
    expect(mySpy).to.have.been.calledOnce;
    expect(mySpy).to.have.been.calledWith('first-call');
    expect(mySpy).to.not.have.been.calledWith('wrong-argument');
  });

  it('should not call the spy if a condition is not met', () => {
    const serviceMethodConditional = (shouldExecute: boolean) => {
      if (shouldExecute) {
        mySpy('executed');
      }
    };

    serviceMethodConditional(false);

    expect(mySpy).to.not.have.been.called;
    expect(mySpy).to.have.callCount(0);
  });
});

view raw JSON →