File tree Expand file tree Collapse file tree 2 files changed +34
-1
lines changed Expand file tree Collapse file tree 2 files changed +34
-1
lines changed Original file line number Diff line number Diff line change
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
+ ```
Original file line number Diff line number Diff line change 1
1
{
2
2
"docs" : {
3
- "Getting Started" : [" intro" , " guiding-principles" ],
3
+ "Getting Started" : [" intro" , " guiding-principles" , " using-fake-timers " ],
4
4
"Frameworks" : [
5
5
{
6
6
"type" : " subcategory" ,
You can’t perform that action at this time.
0 commit comments