FakeTimers

In some cases, when your code uses timers (setTimeout, setInterval, clearTimeout, clearInterval), your tests can become unpredictable, slow and unreliable.

To solve these problems, or if you need to rely on specific timestamps in your code, most testing frameworks offer the option to replace the real timers in your tests with dummy timers. This should be used sporadically and not on a regular basis, as there is some overhead in using them.

When dummy timers are used in tests, all code within the test uses dummy timers.

The common pattern for setting fake timers is usually inside the beforeEach, but if this is not necessary for all tests, you could initialize the faketimers in the first line of code of the Arrange section and remember to reset the timers at the end of the unit test. Here is an example:

    it('GridExTableViewComponent should call the rowDoubleClickEvent on doubleClickHandler', () => {
    //Arrange
    jest.useFakeTimers();
    const spyRowDoubleClickEvent = jest.spyOn(component, 'rowDoubleClickEvent');
    component.currentDataRow = { 'gridEXRowID': '123456789' };
    const event = {};

    //Act
    component.doubleClickHandler(event);
    jest.runOnlyPendingTimers();

    //Assert
    expect(spyRowDoubleClickEvent).toHaveBeenCalled();
    
    jest.useRealTimers();
  });

There are several types of methods to simulate setTimeOut processes: runAllTimers, runOnlyPendingTimers, clearAllTimers... In case of doubts about how to perform any process you can consult the official JEST documentation, Timer Mocks.

Last updated