|
| 1 | +--- |
| 2 | +id: using-fake-timers |
| 3 | +title: Using Fake Timers |
| 4 | +sidebar_label: Using Fake Timers |
| 5 | +--- |
| 6 | + |
| 7 | +In some cases, when your code uses timers (`setTimeout`, `setInterval`, |
| 8 | +`clearTimeout`, `clearInterval`), your tests may become unpredictable, slow and |
| 9 | +flaky. |
| 10 | + |
| 11 | +To solve these problems, or if you need to rely on specific timestamps in your |
| 12 | +code, most testing frameworks offer the option to replace the real timers in |
| 13 | +your tests with fake ones. This should be used sporadically and not on a regular |
| 14 | +basis since using it contains some overhead. |
| 15 | + |
| 16 | +When using fake timers in your tests, all of the code inside your test uses fake |
| 17 | +timers. |
| 18 | +The common pattern to setup fake timers is usually within the `beforeEach`, for |
| 19 | +example: |
| 20 | + |
| 21 | +```js |
| 22 | +// Fake timers using Jest |
| 23 | +beforeEach(() => { |
| 24 | + jest.useFakeTimers() |
| 25 | +}) |
| 26 | +``` |
| 27 | + |
| 28 | +When using fake timers, you need to remember to restore the timers after your |
| 29 | +test runs. |
| 30 | +The main reason to do that is to prevent 3rd party libraries running after your |
| 31 | +test finishes (e.g cleanup functions), from being coupled to your fake timers |
| 32 | +and use real timers instead. |
| 33 | +For that you usually call `useRealTimers` in `afterEach`. |
| 34 | +It's important to also call `runOnlyPendingTimers` before switching to real |
| 35 | +timers. |
| 36 | +This will ensure you flush all the pending timers before you switch to real |
| 37 | +timers. If you don't progress the timers and just switch to real timers, the |
| 38 | +scheduled tasks won't get executed and you'll get an unexpected behavior. |
| 39 | +This is mostly important for 3rd parties that schedule tasks without you being |
| 40 | +aware of it. |
| 41 | +Here's an example of doing that using jest: |
| 42 | + |
| 43 | +```js |
| 44 | +// Running all pending timers and switching to real timers using Jest |
| 45 | +afterEach(() => { |
| 46 | + jest.runOnlyPendingTimers() |
| 47 | + jest.useRealTimers() |
| 48 | +}) |
| 49 | +``` |
0 commit comments