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:
Last updated
Was this helpful?