create a unit test, with chai and sinon available, that will mock or spyon setinterval so that any function under test that may invoke setinterval will not hold the suite running in typescript

To mock or spy on setInterval in a unit test using Chai and Sinon, we can use the fake method provided by Sinon.

Let's assume we want to test a module that contains a function which invokes setInterval and we want to mock setInterval to ensure that our test runs faster, we can do as follows:

index.ts
import { expect } from 'chai';
import Sinon from 'sinon';

describe('Test Suite for someFunction', () => {
  let clock: any;

  beforeEach(() => {
    clock = Sinon.useFakeTimers();
  });

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

  context('when someFunction is called', () => {
    it('should call setInterval once', () => {
      const setIntervalMock = Sinon.stub(window, 'setInterval');
      setIntervalMock.callsFake(() => {});

      // Invoke the function that contains setInterval.
      someFunction();

      expect(setIntervalMock.calledOnce).to.be.true;
    });
  });
});
592 chars
27 lines

In the before and after each hooks, we use Sinon's useFakeTimers and restore methods to create and restore a clock object, which will replace the real setInterval with a fake one.

Then, in the it block, we stub setInterval with Sinon's stub method and pass a fake implementation using callsFake method which will be invoked every time setInterval is called.

Finally, we invoke the function to be tested and use Chai's expect assertion to verify if setInterval was called once.

This way, the test will not hold because we've mocked time-consuming method in our test.

gistlibby LogSnag