Skip to content

Commit

Permalink
docs(fakeTimers): Explain how to use fake timers in testing-library
Browse files Browse the repository at this point in the history
  • Loading branch information
MatanBobi committed Jul 20, 2020
1 parent 01d53fd commit ab42bbd
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
33 changes: 33 additions & 0 deletions docs/using-fake-timers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
---
id: using-fake-timers
title: Using Fake Timers
sidebar_label: Using Fake Timers
---

Using real timers in your tests is less common since they depend on real time
lapse. For that, some testing frameworks offer the option to use fake timers in
your tests so you won't need to depend on real times.

When using fake timers in your tests, all of the code inside your test uses fake
timers. The common pattern to setup fake timers is usually within the
`beforeEach`, here's an example of how to do that in jest:

```js
beforeEach(() => {
jest.useFakeTimers()
})
```

When doing so, you'll probably want to restore the timers after your test runs.
For that you usually call `useRealTimers` in `afterEach`. It's important to
remember that before calling `useRealTimers` you have to `clearAllTimers`. This
will ensure you clear all the timers even if they weren't executed. That way,
your fake timers are encapsulated to your tests only and when we try to cleanup,
we will work with real timers. So you'll need to do something like this:

```js
afterEach(() => {
jest.clearAllTimers()
jest.useRealTimers()
})
```
2 changes: 1 addition & 1 deletion website/sidebars.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"docs": {
"Getting Started": ["intro", "guiding-principles"],
"Getting Started": ["intro", "guiding-principles", "using-fake-timers"],
"Frameworks": [
{
"type": "subcategory",
Expand Down

0 comments on commit ab42bbd

Please sign in to comment.