|
| 1 | +# Test Timing-Based Code With Jest Fake Timers |
| 2 | + |
| 3 | +In real-world code we use timeouts to do things like debouncing and throttling |
| 4 | +of functions. This is really hard to test efficently and accurately with basic |
| 5 | +test runner tooling. |
| 6 | + |
| 7 | +Jest, however, offers some [Timer Mock |
| 8 | +tooling](https://jestjs.io/docs/en/timer-mocks) that removes most of the |
| 9 | +complexity of getting this right. |
| 10 | + |
| 11 | +Here is a method to test: |
| 12 | + |
| 13 | +```javascript |
| 14 | +const doSomethingAfter200ms = doSomething => { |
| 15 | + setTimeout(() => { |
| 16 | + doSomething(); |
| 17 | + }, 200); |
| 18 | +}; |
| 19 | +``` |
| 20 | + |
| 21 | +A test that shows this to work would have to observe `doSomething` getting |
| 22 | +called after 200ms. |
| 23 | + |
| 24 | +The following test won't work because the expectation is evaluated before the |
| 25 | +timeout function is triggered. |
| 26 | + |
| 27 | +```javascript |
| 28 | +describe("doSomethingAfter200ms", () => { |
| 29 | + test("does something after 200ms (fail)", () => { |
| 30 | + const doSomething = jest.fn(); |
| 31 | + |
| 32 | + doSomethingAfter200ms(doSomething); |
| 33 | + |
| 34 | + expect(doSomething).toHaveBeenCalled(); |
| 35 | + }); |
| 36 | +}); |
| 37 | +``` |
| 38 | + |
| 39 | +By activating `jest.useFakeTimers()`, we can simulate the passing of 200ms and |
| 40 | +then check that our mocked function was called. |
| 41 | + |
| 42 | +```javascript |
| 43 | +jest.useFakeTimers(); |
| 44 | + |
| 45 | +describe("doSomethingAfter200ms", () => { |
| 46 | + test("does something after 200ms (pass)", () => { |
| 47 | + const doSomething = jest.fn(); |
| 48 | + |
| 49 | + doSomethingAfter200ms(doSomething); |
| 50 | + |
| 51 | + jest.advanceTimersByTime(201); |
| 52 | + |
| 53 | + expect(doSomething).toHaveBeenCalled(); |
| 54 | + }); |
| 55 | +}); |
| 56 | +``` |
| 57 | + |
| 58 | +Jest's function mocks and timer mocks make this possible. |
0 commit comments