The native timer functions (i.e.,
clearInterval) are less than ideal for a testing environment since they depend on real time to elapse. Jest pode trocar temporizadores por funções que permitem controlar a passagem do tempo. Great Scott!
Here we enable fake timers by calling
jest.useFakeTimers();. This mocks out setTimeout and other timer functions with mock functions. If running multiple tests inside of one file or describe block,
jest.useFakeTimers(); can be called before each test manually or with a setup function such as
beforeEach. Not doing so will result in the internal usage counter not being reset.
Another test we might want to write for this module is one that asserts that the callback is called after 1 second. To do this, we're going to use Jest's timer control APIs to fast-forward time right in the middle of the test:
There are also scenarios where you might have a recursive timer -- that is a timer that sets a new timer in its own callback. For these, running all the timers would be an endless loop… so something like
jest.runAllTimers() is not desirable. Para esses casos, você pode usar
advanceTimersByTime no Jest 22.0.0#
Outra possibilidade é usar o
jest.advanceTimersByTime(msToRun). When this API is called, all timers are advanced by
msToRun milliseconds. When this API is called, all timers are advanced by
msToRun milliseconds. All pending "macro-tasks" that have been queued via setTimeout() or setInterval(), and would be executed during this time frame, will be executed.
Lastly, it may occasionally be useful in some tests to be able to clear all of the pending timers. For this, we have
The code for this example is available at examples/timer.