What's the difference between Stubs and Fakes?

Viewed 107

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().

0 Answers
Related