Skip to content

Commit ab42bbd

Browse files
committed
docs(fakeTimers): Explain how to use fake timers in testing-library
Relates to testing-library/react-testing-library#743
1 parent 01d53fd commit ab42bbd

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

docs/using-fake-timers.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
---
2+
id: using-fake-timers
3+
title: Using Fake Timers
4+
sidebar_label: Using Fake Timers
5+
---
6+
7+
Using real timers in your tests is less common since they depend on real time
8+
lapse. For that, some testing frameworks offer the option to use fake timers in
9+
your tests so you won't need to depend on real times.
10+
11+
When using fake timers in your tests, all of the code inside your test uses fake
12+
timers. The common pattern to setup fake timers is usually within the
13+
`beforeEach`, here's an example of how to do that in jest:
14+
15+
```js
16+
beforeEach(() => {
17+
jest.useFakeTimers()
18+
})
19+
```
20+
21+
When doing so, you'll probably want to restore the timers after your test runs.
22+
For that you usually call `useRealTimers` in `afterEach`. It's important to
23+
remember that before calling `useRealTimers` you have to `clearAllTimers`. This
24+
will ensure you clear all the timers even if they weren't executed. That way,
25+
your fake timers are encapsulated to your tests only and when we try to cleanup,
26+
we will work with real timers. So you'll need to do something like this:
27+
28+
```js
29+
afterEach(() => {
30+
jest.clearAllTimers()
31+
jest.useRealTimers()
32+
})
33+
```

website/sidebars.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"docs": {
3-
"Getting Started": ["intro", "guiding-principles"],
3+
"Getting Started": ["intro", "guiding-principles", "using-fake-timers"],
44
"Frameworks": [
55
{
66
"type": "subcategory",

0 commit comments

Comments
 (0)