source: frontend/node_modules/@sinonjs/fake-timers/README.md

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 13 days ago

Fix frontend appearance

  • Property mode set to 100644
File size: 16.8 KB
Line 
1# `@sinonjs/fake-timers`
2
3[![CircleCI](https://circleci.com/gh/sinonjs/fake-timers.svg?style=svg)](https://circleci.com/gh/sinonjs/fake-timers)
4[![codecov](https://codecov.io/gh/sinonjs/fake-timers/branch/master/graph/badge.svg)](https://codecov.io/gh/sinonjs/fake-timers)
5<a href="CODE_OF_CONDUCT.md"><img src="https://img.shields.io/badge/Contributor%20Covenant-v2.0%20adopted-ff69b4.svg" alt="Contributor Covenant" /></a>
6
7JavaScript implementation of the timer APIs; `setTimeout`, `clearTimeout`, `setImmediate`, `clearImmediate`, `setInterval`, `clearInterval`, `requestAnimationFrame`, `cancelAnimationFrame`, `requestIdleCallback`, and `cancelIdleCallback`, along with a clock instance that controls the flow of time. FakeTimers also provides a `Date` implementation that gets its time from the clock.
8
9In addition in browser environment `@sinonjs/fake-timers` provides a `performance` implementation that gets its time from the clock. In Node environments FakeTimers provides a `nextTick` implementation that is synchronized with the clock - and a `process.hrtime` shim that works with the clock.
10
11`@sinonjs/fake-timers` can be used to simulate passing time in automated tests and other
12situations where you want the scheduling semantics, but don't want to actually
13wait.
14
15`@sinonjs/fake-timers` is extracted from [Sinon.JS](https://github.com/sinonjs/sinon.js) and targets the [same runtimes](https://sinonjs.org/releases/latest/#supported-runtimes).
16
17## Autocomplete, IntelliSense and TypeScript definitions
18
19Version 7 introduced JSDoc to the codebase. This should provide autocomplete and type suggestions in supporting IDEs. If you need more elaborate type support, TypeScript definitions for the Sinon projects are independently maintained by the Definitely Types community:
20
21```
22npm install -D @types/sinonjs__fake-timers
23```
24
25## Installation
26
27`@sinonjs/fake-timers` can be used in both Node and browser environments. Installation is as easy as
28
29```sh
30npm install @sinonjs/fake-timers
31```
32
33If you want to use `@sinonjs/fake-timers` in a browser you can either build your own bundle or use [Skypack](https://www.skypack.dev).
34
35## Usage
36
37To use `@sinonjs/fake-timers`, create a new clock, schedule events on it using the timer
38functions and pass time using the `tick` method.
39
40```js
41// In the browser distribution, a global `FakeTimers` is already available
42var FakeTimers = require("@sinonjs/fake-timers");
43var clock = FakeTimers.createClock();
44
45clock.setTimeout(function () {
46 console.log(
47 "The poblano is a mild chili pepper originating in the state of Puebla, Mexico."
48 );
49}, 15);
50
51// ...
52
53clock.tick(15);
54```
55
56Upon executing the last line, an interesting fact about the
57[Poblano](https://en.wikipedia.org/wiki/Poblano) will be printed synchronously to
58the screen. If you want to simulate asynchronous behavior, you have to use your
59imagination when calling the various functions.
60
61The `next`, `runAll`, `runToFrame`, and `runToLast` methods are available to advance the clock. See the
62API Reference for more details.
63
64### Faking the native timers
65
66When using `@sinonjs/fake-timers` to test timers, you will most likely want to replace the native
67timers such that calling `setTimeout` actually schedules a callback with your
68clock instance, not the browser's internals.
69
70Calling `install` with no arguments achieves this. You can call `uninstall`
71later to restore things as they were again.
72
73```js
74// In the browser distribution, a global `FakeTimers` is already available
75var FakeTimers = require("@sinonjs/fake-timers");
76
77var clock = FakeTimers.install();
78// Equivalent to
79// var clock = FakeTimers.install(typeof global !== "undefined" ? global : window);
80
81setTimeout(fn, 15); // Schedules with clock.setTimeout
82
83clock.uninstall();
84// setTimeout is restored to the native implementation
85```
86
87To hijack timers in another context pass it to the `install` method.
88
89```js
90var FakeTimers = require("@sinonjs/fake-timers");
91var context = {
92 setTimeout: setTimeout, // By default context.setTimeout uses the global setTimeout
93};
94var clock = FakeTimers.withGlobal(context).install();
95
96context.setTimeout(fn, 15); // Schedules with clock.setTimeout
97
98clock.uninstall();
99// context.setTimeout is restored to the original implementation
100```
101
102Usually you want to install the timers onto the global object, so call `install`
103without arguments.
104
105#### Automatically incrementing mocked time
106
107FakeTimers supports the possibility to attach the faked timers to any change
108in the real system time. This means that there is no need to `tick()` the
109clock in a situation where you won't know **when** to call `tick()`.
110
111Please note that this is achieved using the original setImmediate() API at a certain
112configurable interval `config.advanceTimeDelta` (default: 20ms). Meaning time would
113be incremented every 20ms, not in real time.
114
115An example would be:
116
117```js
118var FakeTimers = require("@sinonjs/fake-timers");
119var clock = FakeTimers.install({
120 shouldAdvanceTime: true,
121 advanceTimeDelta: 40,
122});
123
124setTimeout(() => {
125 console.log("this just timed out"); //executed after 40ms
126}, 30);
127
128setImmediate(() => {
129 console.log("not so immediate"); //executed after 40ms
130});
131
132setTimeout(() => {
133 console.log("this timed out after"); //executed after 80ms
134 clock.uninstall();
135}, 50);
136```
137
138## API Reference
139
140### `var clock = FakeTimers.createClock([now[, loopLimit]])`
141
142Creates a clock. The default
143[epoch](https://en.wikipedia.org/wiki/Epoch_%28reference_date%29) is `0`.
144
145The `now` argument may be a number (in milliseconds) or a Date object.
146
147The `loopLimit` argument sets the maximum number of timers that will be run when calling `runAll()` before assuming that we have an infinite loop and throwing an error. The default is `1000`.
148
149### `var clock = FakeTimers.install([config])`
150
151Installs FakeTimers using the specified config (otherwise with epoch `0` on the global scope). The following configuration options are available
152
153| Parameter | Type | Default | Description |
154| -------------------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
155| `config.now` | Number/Date | 0 | installs FakeTimers with the specified unix epoch |
156| `config.toFake` | String[] | ["setTimeout", "clearTimeout", "setImmediate", "clearImmediate","setInterval", "clearInterval", "Date", "requestAnimationFrame", "cancelAnimationFrame", "requestIdleCallback", "cancelIdleCallback", "hrtime"] | an array with explicit function names to hijack. _When not set, FakeTimers will automatically fake all methods **except** `nextTick`_ e.g., `FakeTimers.install({ toFake: ["setTimeout","nextTick"]})` will fake only `setTimeout` and `nextTick` |
157| `config.loopLimit` | Number | 1000 | the maximum number of timers that will be run when calling runAll() |
158| `config.shouldAdvanceTime` | Boolean | false | tells FakeTimers to increment mocked time automatically based on the real system time shift (e.g. the mocked time will be incremented by 20ms for every 20ms change in the real system time) |
159| `config.advanceTimeDelta` | Number | 20 | relevant only when using with `shouldAdvanceTime: true`. increment mocked time by `advanceTimeDelta` ms every `advanceTimeDelta` ms change in the real system time. |
160| `config.shouldClearNativeTimers` | Boolean | false | tells FakeTimers to clear 'native' (i.e. not fake) timers by delegating to their respective handlers. These are not cleared by default, leading to potentially unexpected behavior if timers existed prior to installing FakeTimers. |
161
162### `var id = clock.setTimeout(callback, timeout)`
163
164Schedules the callback to be fired once `timeout` milliseconds have ticked by.
165
166In Node.js `setTimeout` returns a timer object. FakeTimers will do the same, however
167its `ref()` and `unref()` methods have no effect.
168
169In browsers a timer ID is returned.
170
171### `clock.clearTimeout(id)`
172
173Clears the timer given the ID or timer object, as long as it was created using
174`setTimeout`.
175
176### `var id = clock.setInterval(callback, timeout)`
177
178Schedules the callback to be fired every time `timeout` milliseconds have ticked
179by.
180
181In Node.js `setInterval` returns a timer object. FakeTimers will do the same, however
182its `ref()` and `unref()` methods have no effect.
183
184In browsers a timer ID is returned.
185
186### `clock.clearInterval(id)`
187
188Clears the timer given the ID or timer object, as long as it was created using
189`setInterval`.
190
191### `var id = clock.setImmediate(callback)`
192
193Schedules the callback to be fired once `0` milliseconds have ticked by. Note
194that you'll still have to call `clock.tick()` for the callback to fire. If
195called during a tick the callback won't fire until `1` millisecond has ticked
196by.
197
198In Node.js `setImmediate` returns a timer object. FakeTimers will do the same,
199however its `ref()` and `unref()` methods have no effect.
200
201In browsers a timer ID is returned.
202
203### `clock.clearImmediate(id)`
204
205Clears the timer given the ID or timer object, as long as it was created using
206`setImmediate`.
207
208### `clock.requestAnimationFrame(callback)`
209
210Schedules the callback to be fired on the next animation frame, which runs every
21116 ticks. Returns an `id` which can be used to cancel the callback. This is
212available in both browser & node environments.
213
214### `clock.cancelAnimationFrame(id)`
215
216Cancels the callback scheduled by the provided id.
217
218### `clock.requestIdleCallback(callback[, timeout])`
219
220Queued the callback to be fired during idle periods to perform background and low priority work on the main event loop. Callbacks which have a timeout option will be fired no later than time in milliseconds. Returns an `id` which can be used to cancel the callback.
221
222### `clock.cancelIdleCallback(id)`
223
224Cancels the callback scheduled by the provided id.
225
226### `clock.countTimers()`
227
228Returns the number of waiting timers. This can be used to assert that a test
229finishes without leaking any timers.
230
231### `clock.hrtime(prevTime?)`
232
233Only available in Node.js, mimicks process.hrtime().
234
235### `clock.nextTick(callback)`
236
237Only available in Node.js, mimics `process.nextTick` to enable completely synchronous testing flows.
238
239### `clock.performance.now()`
240
241Only available in browser environments, mimicks performance.now().
242
243### `clock.tick(time)` / `await clock.tickAsync(time)`
244
245Advance the clock, firing callbacks if necessary. `time` may be the number of
246milliseconds to advance the clock by or a human-readable string. Valid string
247formats are `"08"` for eight seconds, `"01:00"` for one minute and `"02:34:10"`
248for two hours, 34 minutes and ten seconds.
249
250The `tickAsync()` will also break the event loop, allowing any scheduled promise
251callbacks to execute _before_ running the timers.
252
253### `clock.next()` / `await clock.nextAsync()`
254
255Advances the clock to the the moment of the first scheduled timer, firing it.
256
257The `nextAsync()` will also break the event loop, allowing any scheduled promise
258callbacks to execute _before_ running the timers.
259
260### `clock.reset()`
261
262Removes all timers and ticks without firing them, and sets `now` to `config.now`
263that was provided to `FakeTimers.install` or to `0` if `config.now` was not provided.
264Useful to reset the state of the clock without having to `uninstall` and `install` it.
265
266### `clock.runAll()` / `await clock.runAllAsync()`
267
268This runs all pending timers until there are none remaining. If new timers are added while it is executing they will be run as well.
269
270This makes it easier to run asynchronous tests to completion without worrying about the number of timers they use, or the delays in those timers.
271
272It runs a maximum of `loopLimit` times after which it assumes there is an infinite loop of timers and throws an error.
273
274The `runAllAsync()` will also break the event loop, allowing any scheduled promise
275callbacks to execute _before_ running the timers.
276
277### `clock.runMicrotasks()`
278
279This runs all pending microtasks scheduled with `nextTick` but none of the timers and is mostly useful for libraries using FakeTimers underneath and for running `nextTick` items without any timers.
280
281### `clock.runToFrame()`
282
283Advances the clock to the next frame, firing all scheduled animation frame callbacks,
284if any, for that frame as well as any other timers scheduled along the way.
285
286### `clock.runToLast()` / `await clock.runToLastAsync()`
287
288This takes note of the last scheduled timer when it is run, and advances the
289clock to that time firing callbacks as necessary.
290
291If new timers are added while it is executing they will be run only if they
292would occur before this time.
293
294This is useful when you want to run a test to completion, but the test recursively
295sets timers that would cause `runAll` to trigger an infinite loop warning.
296
297The `runToLastAsync()` will also break the event loop, allowing any scheduled promise
298callbacks to execute _before_ running the timers.
299
300### `clock.setSystemTime([now])`
301
302This simulates a user changing the system clock while your program is running.
303It affects the current time but it does not in itself cause e.g. timers to fire;
304they will fire exactly as they would have done without the call to
305setSystemTime().
306
307### `clock.uninstall()`
308
309Restores the original methods of the native timers or the methods on the object
310that was passed to `FakeTimers.withGlobal`
311
312### `Date`
313
314Implements the `Date` object but using the clock to provide the correct time.
315
316### `Performance`
317
318Implements the `now` method of the [`Performance`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/now) object but using the clock to provide the correct time. Only available in environments that support the Performance object (browsers mostly).
319
320### `FakeTimers.withGlobal`
321
322In order to support creating clocks based on separate or sandboxed environments (such as JSDOM), FakeTimers exports a factory method which takes single argument `global`, which it inspects to figure out what to mock and what features to support. When invoking this function with a global, you will get back an object with `timers`, `createClock` and `install` - same as the regular FakeTimers exports only based on the passed in global instead of the global environment.
323
324## Running tests
325
326FakeTimers has a comprehensive test suite. If you're thinking of contributing bug
327fixes or suggesting new features, you need to make sure you have not broken any
328tests. You are also expected to add tests for any new behavior.
329
330### On node:
331
332```sh
333npm test
334```
335
336Or, if you prefer more verbose output:
337
338```
339$(npm bin)/mocha ./test/fake-timers-test.js
340```
341
342### In the browser
343
344[Mochify](https://github.com/mantoni/mochify.js) is used to run the tests in
345PhantomJS. Make sure you have `phantomjs` installed. Then:
346
347```sh
348npm test-headless
349```
350
351## License
352
353BSD 3-clause "New" or "Revised" License (see LICENSE file)
Note: See TracBrowser for help on using the repository browser.