Sinon Testing Best Practices


This post goes over Sinon testing best practices:

sandbox

Create a new sandbox instead of using the default one.

❌ Bad:

sinon.stub(obj, 'method');

✅ Good:

const sandbox = sinon.createSandbox();
sandbox.stub(obj, 'method');

describe

Create a sandbox inside of the describe block:

describe(() => {
  const sandbox = sinon.createSandbox();
});

This prevents mocked objects from leaking to other tests.

each

It’s good practice to set up and restore all fakes for each test:

beforeEach(() => {
  sandbox.stub(obj, 'method');
});

afterEach(() => {
  sandbox.restore();
});

assert

Use Sinon’s built-in assertions to display more robust error messages.

❌ Bad:

expect(spy).toBeCalled(1);

✅ Good:

sinon.assert.called(spy);

match

Use matchers to match partial object.

❌ Bad:

expect(spy.getCall(0).args[0].foo).toEqual('bar');

✅ Good:

sinon.assert.calledWith(spy, sinon.match({ foo: 'bar' }));

type

When using TypeScript, type the stubbed member:

let stub: sinon.SinonStubbedMember<typeof obj.method>;

Or type cast to a stub:

stub as Sinon.Stub;

Use Type Assertion if the provided value is different:

stub.returns(value as string);


Please support this site and join our Discord!