Heroic Testing with Sinon

Spies

Stubs

Mocks

?

?

?

?

?

?

All Three

  • Are tools to "fake" different methods
  • Can be utilised to verify code pathways by using callCounts and 

All Three

  • Are tools to "fake" different methods
  • Can be utilised to verify code pathways by using callCounts and 

Spy Api

Stub Api

Implements

Expectations

Mock Api

Implements

Utilizes

All Three

  • Are tools to "fake" different methods
  • Can be utilised to verify code pathways by using callCounts and 

Spy Api

Stub Api

Implements

Expectations

Mock Api

Implements

Utilizes

Fake methods, no preprogrammed behaviour

Fake methods, with preprogrammed behaviour

Fake methods, preprogrammed behaviour, that throws exceptions where chained expectations are not matched

Spy

Fake a method. Can't force a function to substitute a return value, throw an exception, resolve or reject.

 

 

Spy

class Counter {
  constructor() {
    this.count = 0;
  }

  increment() {
    this.count++;
  }

  decrement() {
    this.count--;
  }

  countToTen() {
    for (const count = 0; count <= 10; count++)
      this.increment();
  }
}


describe('countToTen', () => {
  it('should call increment 11 times', () => {
    const counter = new Counter();
    const incrementSpy = sinon.spy(counter, 'increment');
    counter.countToTen();
    expect(incrementSpy.callCount).toEqual(11);
    // This resets the state of our spy
    incrementSpy.reset();
    // This removes our spy, allowing the original method to run unimpeded
    incrementSpy.restore();
  });
});

Heroic Testing with Sinon

By em0ney

Heroic Testing with Sinon

  • 815