3

Sinon.js provides Fakes. But I didn't see any essential differences with Stubs. Here is example code under test:

index.ts:

export function main(callback) {
  return callback();
}

index.test.ts:

import sinon from 'sinon';
import { main } from './';

describe('sinon fake vs stub', () => {
  it('should pass when using a sinon stub', () => {
    const callback = sinon.stub().returns('value');
    const actual = main(callback);
    sinon.assert.match(actual, 'value');
    sinon.assert.calledOnce(callback);
  });

  it('should pass when using a sinon fake', () => {
    const callback = sinon.fake.returns('value');
    const actual = main(callback);
    sinon.assert.match(actual, 'value');
    sinon.assert.calledOnce(callback);
  });
});

test results:

  sinon fake vs stub
    ✓ should pass when using a sinon stub
    ✓ should pass when using a sinon fake


  2 passing (9ms)

For sinon.fake.throws(value);, sinon.fake.resolves(value);, sinon.fake.yields([value1, ..., valueN]); APIs and so on. I can also use sinon.stubs() do these.

I use sinon.stubs() a lot, the documentation of Fakes doesn't give special scenes can only use fakes. I can currently test all scenarios using sinon.stubs().

Lin Du
  • 88,126
  • 95
  • 281
  • 483
  • The documentation does say "*Unlike `sinon.spy` and `sinon.stub` methods, the `sinon.fake` API knows only how to create fakes, and doesn’t concern itself with plugging them into the system under test*" so, it seems the fakes are *only* fake implementations of functions, while stubs also includes the option to actually add them to other objects. Not sure if that's entirely correct but that's the sense I got from looking at the doc. I will not be surprised if stubs actually uses fakes under the hood. – VLAZ Mar 20 '20 at 07:56

0 Answers0