From ab42bbd7e12798f063de66886e3a32bca4d657f2 Mon Sep 17 00:00:00 2001 From: Matan Borenkraout Date: Mon, 20 Jul 2020 13:34:03 +0300 Subject: [PATCH] docs(fakeTimers): Explain how to use fake timers in testing-library Relates to https://github.com/testing-library/react-testing-library/pull/743 --- docs/using-fake-timers.md | 33 +++++++++++++++++++++++++++++++++ website/sidebars.json | 2 +- 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 docs/using-fake-timers.md diff --git a/docs/using-fake-timers.md b/docs/using-fake-timers.md new file mode 100644 index 00000000..c9203fc1 --- /dev/null +++ b/docs/using-fake-timers.md @@ -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() +}) +``` diff --git a/website/sidebars.json b/website/sidebars.json index be00e320..d2dea8cb 100755 --- a/website/sidebars.json +++ b/website/sidebars.json @@ -1,6 +1,6 @@ { "docs": { - "Getting Started": ["intro", "guiding-principles"], + "Getting Started": ["intro", "guiding-principles", "using-fake-timers"], "Frameworks": [ { "type": "subcategory",