L'objet Jest
The jest object is automatically in scope within every test file. The methods in the jest object help create mocks and let you control Jest's overall behavior. It can also be imported explicitly by via import {jest} from '@jest/globals'.
Les exemples TypeScript de cette page ne fonctionneront comme documenté que si vous importez explicitement les API Jest :
import {expect, jest, test} from '@jest/globals';
Consult the Getting Started guide for details on how to setup Jest with TypeScript.
Méthodes
- Modules simulés
jest.disableAutomock()jest.enableAutomock()jest.createMockFromModule(moduleName)jest.mock(moduleName, factory, options)jest.Mocked<Source>jest.mocked(source, options?)jest.unmock(moduleName)jest.deepUnmock(moduleName)jest.doMock(moduleName, factory, options)jest.dontMock(moduleName)jest.setMock(moduleName, moduleExports)jest.requireActual(moduleName)jest.requireMock(moduleName)jest.resetModules()jest.isolateModules(fn)jest.isolateModulesAsync(fn)
- Fonctions simulées
- Faux temporisateurs
jest.useFakeTimers(fakeTimersConfig?)jest.useRealTimers()jest.runAllTicks()jest.runAllTimers()jest.runAllTimersAsync()jest.runAllImmediates()jest.advanceTimersByTime(msToRun)jest.advanceTimersByTimeAsync(msToRun)jest.runOnlyPendingTimers()jest.runOnlyPendingTimersAsync()jest.advanceTimersToNextTimer(steps)jest.advanceTimersToNextTimerAsync(steps)jest.clearAllTimers()jest.getTimerCount()jest.now()jest.setSystemTime(now?: number | Date)jest.getRealSystemTime()
- Divers
Modules simulés
jest.disableAutomock()
Désactive la simulation automatique dans le chargeur de module.
Automatic mocking should be enabled via automock configuration option for this method to have any effect. Also see documentation of the configuration option for more details.
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
automock: true,
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
automock: true,
};
export default config;
After disableAutomock() is called, all require()s will return the real versions of each module (rather than a mocked version).
export default {
authorize: () => {
return 'token';
},
};
import utils from '../utils';
jest.disableAutomock();
test('original implementation', () => {
// now we have the original implementation,
// even if we set the automocking in a jest configuration
expect(utils.authorize()).toBe('token');
});
Cela est généralement utile lorsque le nombre de dépendances que vous souhaitez simuler est bien inférieur au nombre de dépendances que vous ne souhaitez pas. Par exemple, si vous écrivez un test pour un module qui utilise un grand nombre de dépendances qui peuvent être raisonnablement classées comme des « détails d'implémentation » du module, alors vous ne voulez probablement pas les simuler.
Examples of dependencies that might be considered "implementation details" are things ranging from language built-ins (e.g. Array.prototype methods) to highly common utility methods (e.g. underscore, lodash, array utilities, etc) and entire libraries like React.js.
Returns the jest object for chaining.
When using babel-jest, calls to disableAutomock() will automatically be hoisted to the top of the code block. Use autoMockOff() if you want to explicitly avoid this behavior.
jest.enableAutomock()
Active la simulation automatique dans le chargeur de module.
For more details on automatic mocking see documentation of automock configuration option.
Exemple :
export default {
authorize: () => {
return 'token';
},
isAuthorized: secret => secret === 'wizard',
};
jest.enableAutomock();
import utils from '../utils';
test('original implementation', () => {
// now we have the mocked implementation,
expect(utils.authorize._isMockFunction).toBeTruthy();
expect(utils.isAuthorized._isMockFunction).toBeTruthy();
});
Returns the jest object for chaining.
When using babel-jest, calls to enableAutomock will automatically be hoisted to the top of the code block. Use autoMockOn if you want to explicitly avoid this behavior.
jest.createMockFromModule(moduleName)
Avec le nom d'un module, utilisez le système de simulation automatique pour générer pour vous une version simulée du module.
This is useful when you want to create a manual mock that extends the automatic mock's behavior:
- JavaScript
- TypeScript
module.exports = {
authorize: () => {
return 'token';
},
isAuthorized: secret => secret === 'wizard',
};
const utils = jest.createMockFromModule('../utils');
utils.isAuthorized = jest.fn(secret => secret === 'not wizard');
test('implementation created by jest.createMockFromModule', () => {
expect(jest.isMockFunction(utils.authorize)).toBe(true);
expect(utils.isAuthorized('not wizard')).toBe(true);
});
export const utils = {
authorize: () => {
return 'token';
},
isAuthorized: (secret: string) => secret === 'wizard',
};
const {utils} =
jest.createMockFromModule<typeof import('../utils')>('../utils');
utils.isAuthorized = jest.fn((secret: string) => secret === 'not wizard');
test('implementation created by jest.createMockFromModule', () => {
expect(jest.isMockFunction(utils.authorize)).toBe(true);
expect(utils.isAuthorized('not wizard')).toBe(true);
});
This is how createMockFromModule will mock the following data types:
Function
Creates a new mock function. The new function has no formal parameters and when called will return undefined. This functionality also applies to async functions.
Class
Crée une nouvelle classe. L'interface de la classe originale est maintenue, toutes les fonctions et propriétés des membres de la classe seront simulées.
Object
Crée un nouvel objet profondément cloné. Les clés de l'objet sont maintenues et leurs valeurs sont simulées.
Array
Crée un nouveau tableau vide, ignorant l'original.
Primitives
Crée une nouvelle propriété avec la même valeur primitive que la propriété originale.
Exemple :
module.exports = {
function: function square(a, b) {
return a * b;
},
asyncFunction: async function asyncSquare(a, b) {
const result = (await a) * b;
return result;
},
class: new (class Bar {
constructor() {
this.array = [1, 2, 3];
}
foo() {}
})(),
object: {
baz: 'foo',
bar: {
fiz: 1,
buzz: [1, 2, 3],
},
},
array: [1, 2, 3],
number: 123,
string: 'baz',
boolean: true,
symbol: Symbol.for('a.b.c'),
};
const example = jest.createMockFromModule('../example');
test('should run example code', () => {
// creates a new mocked function with no formal arguments.
expect(example.function.name).toBe('square');
expect(example.function).toHaveLength(0);
// async functions get the same treatment as standard synchronous functions.
expect(example.asyncFunction.name).toBe('asyncSquare');
expect(example.asyncFunction).toHaveLength(0);
// creates a new class with the same interface, member functions and properties are mocked.
expect(example.class.constructor.name).toBe('Bar');
expect(example.class.foo.name).toBe('foo');
expect(example.class.array).toHaveLength(0);
// creates a deeply cloned version of the original object.
expect(example.object).toEqual({
baz: 'foo',
bar: {
fiz: 1,
buzz: [],
},
});
// creates a new empty array, ignoring the original array.
expect(example.array).toHaveLength(0);
// creates a new property with the same primitive value as the original property.
expect(example.number).toBe(123);
expect(example.string).toBe('baz');
expect(example.boolean).toBe(true);
expect(example.symbol).toEqual(Symbol.for('a.b.c'));
});
jest.mock(moduleName, factory, options)
Simule un module avec une version simulée automatiquement lorsqu'il est exigé. factory and options are optional. Par exemple :
module.exports = () => 'banana';
jest.mock('../banana');
const banana = require('../banana'); // banana will be explicitly mocked.
banana(); // will return 'undefined' because the function is auto-mocked.
Le second argument peut être utilisé pour spécifier une factory de modules explicite qui est exécutée au lieu d'utiliser la fonctionnalité de simulation automatique de Jest :
- JavaScript
- TypeScript
jest.mock('../moduleName', () => {
return jest.fn(() => 42);
});
// This runs the function specified as second argument to `jest.mock`.
const moduleName = require('../moduleName');
moduleName(); // Will return '42';
// The optional type argument provides typings for the module factory
jest.mock<typeof import('../moduleName')>('../moduleName', () => {
return jest.fn(() => 42);
});
// This runs the function specified as second argument to `jest.mock`.
const moduleName = require('../moduleName');
moduleName(); // Will return '42';
When using the factory parameter for an ES6 module with a default export, the __esModule: true property needs to be specified. Cette propriété est normalement générée par Babel / TypeScript, mais ici elle doit être définie manuellement. When importing a default export, it's an instruction to import the property named default from the export object:
import moduleName, {foo} from '../moduleName';
jest.mock('../moduleName', () => {
return {
__esModule: true,
default: jest.fn(() => 42),
foo: jest.fn(() => 43),
};
});
moduleName(); // Will return 42
foo(); // Will return 43
Le troisième argument peut être utilisé pour créer des simulations virtuels - des simulations de modules qui n'existent nulle part dans le système :
jest.mock(
'../moduleName',
() => {
/*
* Custom implementation of a module that doesn't exist in JS,
* like a generated module or a native module in react-native.
*/
},
{virtual: true},
);
Importing a module in a setup file (as specified by setupFilesAfterEnv) will prevent mocking for the module in question, as well as all the modules that it imports.
Modules that are mocked with jest.mock are mocked only for the file that calls jest.mock. Un autre fichier qui importe le module obtiendra l'implémentation originale même s'il est exécuté après le fichier de test qui simule le module.
Returns the jest object for chaining.
Écriture des tests en TypeScript ? Use the jest.Mocked utility type or the jest.mocked() helper method to have your mocked modules typed.
jest.Mocked<Source>
See TypeScript Usage chapter of Mock Functions page for documentation.
jest.mocked(source, options?)
See TypeScript Usage chapter of Mock Functions page for documentation.
jest.unmock(moduleName)
Indicates that the module system should never return a mocked version of the specified module from require() (e.g. that it should always return the real module).
L'utilisation la plus fréquente de cette API est de spécifier le module qu'un test donné a l'intention de tester (et donc ne veut pas être automatiquement simulé).
Returns the jest object for chaining.
jest.deepUnmock(moduleName)
Indicates that the module system should never return a mocked version of the specified module and its dependencies.
Returns the jest object for chaining.
jest.doMock(moduleName, factory, options)
When using babel-jest, calls to mock will automatically be hoisted to the top of the code block. Utilisez cette méthode si vous voulez éviter explicitement ce comportement.
Un exemple où cela est utile est lorsque vous voulez simuler un module différemment dans le même fichier :
- JavaScript
- TypeScript
beforeEach(() => {
jest.resetModules();
});
test('moduleName 1', () => {
jest.doMock('../moduleName', () => {
return jest.fn(() => 1);
});
const moduleName = require('../moduleName');
expect(moduleName()).toBe(1);
});
test('moduleName 2', () => {
jest.doMock('../moduleName', () => {
return jest.fn(() => 2);
});
const moduleName = require('../moduleName');
expect(moduleName()).toBe(2);
});
beforeEach(() => {
jest.resetModules();
});
test('moduleName 1', () => {
// The optional type argument provides typings for the module factory
jest.doMock<typeof import('../moduleName')>('../moduleName', () => {
return jest.fn(() => 1);
});
const moduleName = require('../moduleName');
expect(moduleName()).toBe(1);
});
test('moduleName 2', () => {
jest.doMock<typeof import('../moduleName')>('../moduleName', () => {
return jest.fn(() => 2);
});
const moduleName = require('../moduleName');
expect(moduleName()).toBe(2);
});
Using jest.doMock() with ES6 imports requires additional steps. Follow these if you don't want to use require in your tests:
- We have to specify the
__esModule: trueproperty (see thejest.mock()API for more information). - Static ES6 module imports are hoisted to the top of the file, so instead we have to import them dynamically using
import(). - Enfin, nous avons besoin d'un environnement qui soutienne l'importation dynamique. Please see Using Babel for the initial setup. Then add the plugin babel-plugin-dynamic-import-node, or an equivalent, to your Babel config to enable dynamic importing in Node.
beforeEach(() => {
jest.resetModules();
});
test('moduleName 1', () => {
jest.doMock('../moduleName', () => {
return {
__esModule: true,
default: 'default1',
foo: 'foo1',
};
});
return import('../moduleName').then(moduleName => {
expect(moduleName.default).toBe('default1');
expect(moduleName.foo).toBe('foo1');
});
});
test('moduleName 2', () => {
jest.doMock('../moduleName', () => {
return {
__esModule: true,
default: 'default2',
foo: 'foo2',
};
});
return import('../moduleName').then(moduleName => {
expect(moduleName.default).toBe('default2');
expect(moduleName.foo).toBe('foo2');
});
});
Returns the jest object for chaining.
jest.dontMock(moduleName)
When using babel-jest, calls to unmock will automatically be hoisted to the top of the code block. Utilisez cette méthode si vous voulez éviter explicitement ce comportement.
Returns the jest object for chaining.
jest.setMock(moduleName, moduleExports)
Fournit explicitement l'objet simulé que le système de module doit retourner pour le module spécifié.
Il arrive parfois que la simulation générée automatiquement par le système de modules ne soit pas suffisante pour vos besoins de test. Normally under those circumstances you should write a manual mock that is more adequate for the module in question. Cependant, en de très rares occasions, même une simulation manuelle n'est pas adaptée à vos besoins et vous devez construire la simulation vous-même dans votre test.
Dans ces rares cas, vous pouvez utiliser cette API pour remplir manuellement l'emplacement dans le registre des modules fictifs du système de modules.
Returns the jest object for chaining.
It is recommended to use jest.mock() instead. The jest.mock API's second argument is a module factory instead of the expected exported module object.
jest.requireActual(moduleName)
Renvoie le module réel au lieu d'une simulation, en contournant toutes les vérifications pour savoir si le module doit recevoir une implémentation simulée ou non.
- JavaScript
- TypeScript
jest.mock('../myModule', () => {
// Require the original module to not be mocked...
const originalModule = jest.requireActual('../myModule');
return {
__esModule: true, // Use it when dealing with esModules
...originalModule,
getRandom: jest.fn(() => 10),
};
});
const getRandom = require('../myModule').getRandom;
getRandom(); // Always returns 10
jest.mock('../myModule', () => {
// Require the original module to not be mocked...
const originalModule =
jest.requireActual<typeof import('../myModule')>('../myModule');
return {
__esModule: true, // Use it when dealing with esModules
...originalModule,
getRandom: jest.fn(() => 10),
};
});
const getRandom = require('../myModule').getRandom;
getRandom(); // Always returns 10
jest.requireMock(moduleName)
Renvoie un module simulé au lieu du module réel, en contournant toutes les vérifications pour savoir si le module doit être requis normalement ou non.
jest.resetModules()
Réinitialise le registre des modules - le cache de tous les modules requis. Ceci est utile pour isoler les modules où l'état local peut entrer en conflit entre les tests.
Exemple :
const sum1 = require('../sum');
jest.resetModules();
const sum2 = require('../sum');
sum1 === sum2;
// > false (Both sum modules are separate "instances" of the sum module.)
Exemple dans un test :
beforeEach(() => {
jest.resetModules();
});
test('works', () => {
const sum = require('../sum');
});
test('works too', () => {
const sum = require('../sum');
// sum is a different copy of the sum module from the previous test.
});
Returns the jest object for chaining.
jest.isolateModules(fn)
jest.isolateModules(fn) goes a step further than jest.resetModules() and creates a sandbox registry for the modules that are loaded inside the callback function. Ceci est utile pour isoler les modules spécifiques pour chaque test afin que l'état du module local n'entre pas en conflit entre les tests.
let myModule;
jest.isolateModules(() => {
myModule = require('myModule');
});
const otherCopyOfMyModule = require('myModule');
jest.isolateModulesAsync(fn)
jest.isolateModulesAsync() is the equivalent of jest.isolateModules(), but for async callbacks. The caller is expected to await the completion of isolateModulesAsync.
let myModule;
await jest.isolateModulesAsync(async () => {
myModule = await import('myModule');
// do async stuff here
});
const otherCopyOfMyModule = await import('myModule');
Fonctions simulées
jest.fn(implementation?)
Returns a new, unused mock function. En option, prend une implémentation simulée.
const mockFn = jest.fn();
mockFn();
expect(mockFn).toHaveBeenCalled();
// With a mock implementation:
const returnsTrue = jest.fn(() => true);
console.log(returnsTrue()); // true;
See the Mock Functions page for details on TypeScript usage.
jest.isMockFunction(fn)
Détermine si la fonction donnée est une fonction simulée.
jest.replaceProperty(object, propertyKey, value)
Replace object[propertyKey] with a value. The property must already exist on the object. The same property might be replaced multiple times. Returns a Jest replaced property.
To mock properties that are defined as getters or setters, use jest.spyOn(object, methodName, accessType) instead. To mock functions, use jest.spyOn(object, methodName) instead.
All properties replaced with jest.replaceProperty could be restored to the original value by calling jest.restoreAllMocks on afterEach method.
Exemple :
const utils = {
isLocalhost() {
return process.env.HOSTNAME === 'localhost';
},
};
module.exports = utils;
Exemple de test :
const utils = require('./utils');
afterEach(() => {
// restore replaced property
jest.restoreAllMocks();
});
test('isLocalhost returns true when HOSTNAME is localhost', () => {
jest.replaceProperty(process, 'env', {HOSTNAME: 'localhost'});
expect(utils.isLocalhost()).toBe(true);
});
test('isLocalhost returns false when HOSTNAME is not localhost', () => {
jest.replaceProperty(process, 'env', {HOSTNAME: 'not-localhost'});
expect(utils.isLocalhost()).toBe(false);
});
jest.spyOn(object, methodName)
Creates a mock function similar to jest.fn but also tracks calls to object[methodName]. Returns a Jest mock function.
By default, jest.spyOn also calls the spied method. Ceci est un comportement différent de la plupart des autres bibliothèques de test. If you want to overwrite the original function, you can use jest.spyOn(object, methodName).mockImplementation(() => customImplementation) or object[methodName] = jest.fn(() => customImplementation).
Since jest.spyOn is a mock, you could restore the initial state by calling jest.restoreAllMocks in the body of the callback passed to the afterEach hook.
Exemple :
const video = {
play() {
return true;
},
};
module.exports = video;
Exemple de test :
const video = require('./video');
afterEach(() => {
// restore the spy created with spyOn
jest.restoreAllMocks();
});
test('plays video', () => {
const spy = jest.spyOn(video, 'play');
const isPlaying = video.play();
expect(spy).toHaveBeenCalled();
expect(isPlaying).toBe(true);
});
jest.spyOn(object, methodName, accessType?)
Since Jest 22.1.0+, the jest.spyOn method takes an optional third argument of accessType that can be either 'get' or 'set', which proves to be useful when you want to spy on a getter or a setter, respectively.
Exemple :
const video = {
// it's a getter!
get play() {
return true;
},
};
module.exports = video;
const audio = {
_volume: false,
// it's a setter!
set volume(value) {
this._volume = value;
},
get volume() {
return this._volume;
},
};
module.exports = audio;
Exemple de test :
const audio = require('./audio');
const video = require('./video');
afterEach(() => {
// restore the spy created with spyOn
jest.restoreAllMocks();
});
test('plays video', () => {
const spy = jest.spyOn(video, 'play', 'get'); // we pass 'get'
const isPlaying = video.play;
expect(spy).toHaveBeenCalled();
expect(isPlaying).toBe(true);
});
test('plays audio', () => {
const spy = jest.spyOn(audio, 'volume', 'set'); // we pass 'set'
audio.volume = 100;
expect(spy).toHaveBeenCalled();
expect(audio.volume).toBe(100);
});
jest.Replaced<Source>
See TypeScript Usage chapter of Mock Functions page for documentation.
jest.Spied<Source>
See TypeScript Usage chapter of Mock Functions page for documentation.
jest.clearAllMocks()
Clears the mock.calls, mock.instances, mock.contexts and mock.results properties of all mocks. Equivalent to calling .mockClear() on every mocked function.
Returns the jest object for chaining.
jest.resetAllMocks()
Réinitialise l'état de toutes les simulations. Equivalent to calling .mockReset() on every mocked function.
Returns the jest object for chaining.
jest.restoreAllMocks()
Restores all mocks and replaced properties back to their original value. Equivalent to calling .mockRestore() on every mocked function and .restore() on every replaced property. Beware that jest.restoreAllMocks() only works for mocks created with jest.spyOn() and properties replaced with jest.replaceProperty(); other mocks will require you to manually restore them.
Faux temporisateurs
jest.useFakeTimers(fakeTimersConfig?)
Indique à Jest d'utiliser des versions fictives des API globales de date, de performance, de temps et de temporisation. Fake timers implementation is backed by @sinonjs/fake-timers.
Fake timers will swap out Date, performance.now(), queueMicrotask(), setImmediate(), clearImmediate(), setInterval(), clearInterval(), setTimeout(), clearTimeout() with an implementation that gets its time from the fake clock.
In Node environment process.hrtime, process.nextTick() and in JSDOM environment requestAnimationFrame(), cancelAnimationFrame(), requestIdleCallback(), cancelIdleCallback() will be replaced as well.
Options de configuration :
type FakeableAPI =
| 'Date'
| 'hrtime'
| 'nextTick'
| 'performance'
| 'queueMicrotask'
| 'requestAnimationFrame'
| 'cancelAnimationFrame'
| 'requestIdleCallback'
| 'cancelIdleCallback'
| 'setImmediate'
| 'clearImmediate'
| 'setInterval'
| 'clearInterval'
| 'setTimeout'
| 'clearTimeout';
type FakeTimersConfig = {
/**
* If set to `true` all timers will be advanced automatically by 20 milliseconds
* every 20 milliseconds. A custom time delta may be provided by passing a number.
* The default is `false`.
*/
advanceTimers?: boolean | number;
/**
* List of names of APIs that should not be faked. The default is `[]`, meaning
* all APIs are faked.
*/
doNotFake?: Array<FakeableAPI>;
/**
* Use the old fake timers implementation instead of one backed by `@sinonjs/fake-timers`.
* The default is `false`.
*/
legacyFakeTimers?: boolean;
/** Sets current system time to be used by fake timers, in milliseconds. The default is `Date.now()`. */
now?: number | Date;
/**
* The maximum number of recursive timers that will be run when calling `jest.runAllTimers()`.
* The default is `100_000` timers.
*/
timerLimit?: number;
};
Calling jest.useFakeTimers() will use fake timers for all tests within the file, until original timers are restored with jest.useRealTimers().
You can call jest.useFakeTimers() or jest.useRealTimers() from anywhere: top level, inside an test block, etc. Keep in mind that this is a global operation and will affect other tests within the same file. Calling jest.useFakeTimers() once again in the same test file would reset the internal state (e.g. timer count) and reinstall fake timers using the provided options:
test('advance the timers automatically', () => {
jest.useFakeTimers({advanceTimers: true});
// ...
});
test('do not advance the timers and do not fake `performance`', () => {
jest.useFakeTimers({doNotFake: ['performance']});
// ...
});
test('uninstall fake timers for the rest of tests in the file', () => {
jest.useRealTimers();
// ...
});
Pour certaines raisons, il se peut que vous deviez utiliser une ancienne implémentation de faux temporisateurs. Elle peut être activée comme ceci (les options supplémentaires ne sont pas supportées) :
jest.useFakeTimers({
legacyFakeTimers: true,
});
Legacy fake timers will swap out setImmediate(), clearImmediate(), setInterval(), clearInterval(), setTimeout(), clearTimeout() with Jest mock functions. In Node environment process.nextTick() and in JSDOM environment requestAnimationFrame(), cancelAnimationFrame() will be also replaced.
Returns the jest object for chaining.
jest.useRealTimers()
Indique à Jest de restaurer les implémentations originales de la date globale, de la performance, de l'heure et des API de temporisation. For example, you may call jest.useRealTimers() inside afterEach hook to restore timers after each test:
afterEach(() => {
jest.useRealTimers();
});
test('do something with fake timers', () => {
jest.useFakeTimers();
// ...
});
test('do something with real timers', () => {
// ...
});
Returns the jest object for chaining.
jest.runAllTicks()
Exhausts the micro-task queue (usually interfaced in node via process.nextTick).
When this API is called, all pending micro-tasks that have been queued via process.nextTick will be executed. En outre, si ces micro-tâches elles-mêmes planifient de nouvelles micro-tâches, elles seront continuellement libérées jusqu'à ce qu'il n'y ait plus de micro-tâches dans la file d'attente.
jest.runAllTimers()
Exhausts both the macro-task queue (i.e., all tasks queued by setTimeout(), setInterval(), and setImmediate()) and the micro-task queue (usually interfaced in node via process.nextTick).
Lorsque cette API est appelée, toutes les macro-tâches et les micro-tâches en attente seront exécutées. Si ces tâches elles-mêmes planifient de nouvelles tâches, elles seront continuellement libérées jusqu'à ce qu'il n'y ait plus de tâches dans la file d'attente.
This is often useful for synchronously executing setTimeouts during a test in order to synchronously assert about some behavior that would only happen after the setTimeout() or setInterval() callbacks executed. See the Timer mocks doc for more information.
jest.runAllTimersAsync()
Asynchronous equivalent of jest.runAllTimers(). It allows any scheduled promise callbacks to execute before running the timers.
Cette fonction n'est pas disponible lors de l'utilisation de l'ancienne implémentation des faux temporisateurs.
jest.runAllImmediates()
Exhausts all tasks queued by setImmediate().
Cette fonction est disponible uniquement lors de l'utilisation de l'ancienne implémentation des faux temporisateurs.
jest.advanceTimersByTime(msToRun)
Executes only the macro task queue (i.e. all tasks queued by setTimeout() or setInterval() and setImmediate()).
When this API is called, all timers are advanced by msToRun milliseconds. All pending "macro-tasks" that have been queued via setTimeout() or setInterval(), and would be executed within this time frame will be executed. Additionally, if those macro-tasks schedule new macro-tasks that would be executed within the same time frame, those will be executed until there are no more macro-tasks remaining in the queue, that should be run within msToRun milliseconds.
jest.advanceTimersByTimeAsync(msToRun)
Asynchronous equivalent of jest.advanceTimersByTime(msToRun). It allows any scheduled promise callbacks to execute before running the timers.
Cette fonction n'est pas disponible lors de l'utilisation de l'ancienne implémentation des faux temporisateurs.
jest.runOnlyPendingTimers()
Executes only the macro-tasks that are currently pending (i.e., only the tasks that have been queued by setTimeout() or setInterval() up to this point). Si l'une des macro-tâches en cours planifie de nouvelles macro-tâches, ces nouvelles tâches ne seront pas exécutées par cet appel.
This is useful for scenarios such as one where the module being tested schedules a setTimeout() whose callback schedules another setTimeout() recursively (meaning the scheduling never stops). Dans ces scénarios, il est utile de pouvoir avancer dans le temps d'une seule étape à la fois.
jest.runOnlyPendingTimersAsync()
Asynchronous equivalent of jest.runOnlyPendingTimers(). It allows any scheduled promise callbacks to execute before running the timers.
Cette fonction n'est pas disponible lors de l'utilisation de l'ancienne implémentation des faux temporisateurs.
jest.advanceTimersToNextTimer(steps)
Avance tous les temporisateurs en millisecondes nécessaires pour que seuls les prochains timeouts/intervals s'exécutent.
Optionally, you can provide steps, so it will run steps amount of next timeouts/intervals.
jest.advanceTimersToNextTimerAsync(steps)
Asynchronous equivalent of jest.advanceTimersToNextTimer(steps). It allows any scheduled promise callbacks to execute before running the timers.
Cette fonction n'est pas disponible lors de l'utilisation de l'ancienne implémentation des faux temporisateurs.
jest.clearAllTimers()
Supprime tous les temporisateurs en attente du système de temporisation.
Cela signifie que si des temporisateurs ont été programmés (mais n'ont pas encore été exécutés), ils seront effacés et n'auront jamais la possibilité de s'exécuter à l'avenir.
jest.getTimerCount()
Retourne le nombre de temporisateurs fictifs qui restent à exécuter.
jest.now()
Returns the time in ms of the current clock. This is equivalent to Date.now() if real timers are in use, or if Date is mocked. In other cases (such as legacy timers) it may be useful for implementing custom mocks of Date.now(), performance.now(), etc.
jest.setSystemTime(now?: number | Date)
Définit l'heure actuelle du système utilisée par les temporisateurs fictifs. Simule un utilisateur qui change l'horloge du système pendant que votre programme fonctionne. It affects the current time but it does not in itself cause e.g. timers to fire; they will fire exactly as they would have done without the call to jest.setSystemTime().
Cette fonction n'est pas disponible lors de l'utilisation de l'ancienne implémentation des faux temporisateurs.
jest.getRealSystemTime()
When mocking time, Date.now() will also be mocked. Si vous avez besoin pour une raison quelconque d'avoir accès à l'heure réelle, vous pouvez appeler cette fonction.
Cette fonction n'est pas disponible lors de l'utilisation de l'ancienne implémentation des faux temporisateurs.
Divers
jest.getSeed()
Every time Jest runs a seed value is randomly generated which you could use in a pseudorandom number generator or anywhere else.
Use the --showSeed flag to print the seed in the test report summary. To manually set the value of the seed use --seed=<num> CLI argument.
jest.isEnvironmentTornDown()
Returns true if test environment has been torn down.
jest.retryTimes(numRetries, options?)
Exécute les tests échoués n-fois jusqu'à ce qu'ils passent ou jusqu'à ce que le nombre maximum de tentatives soit épuisé.
jest.retryTimes(3);
test('will fail', () => {
expect(true).toBe(false);
});
If logErrorsBeforeRetry option is enabled, error(s) that caused the test to fail will be logged to the console.
jest.retryTimes(3, {logErrorsBeforeRetry: true});
test('will fail', () => {
expect(true).toBe(false);
});
Returns the jest object for chaining.
jest.retryTimes() must be declared at the top level of a test file or in a describe block.
This function is only available with the default jest-circus runner.
jest.setTimeout(timeout)
Définit l'intervalle de temps par défaut (en millisecondes) pour tous les tests et avant/après les hooks dans le fichier de test. Cela n'affecte que le fichier de test à partir duquel cette fonction est appelée. The default timeout interval is 5 seconds if this method is not called.
Exemple :
jest.setTimeout(1000); // 1 seconde
To set timeout intervals on different tests in the same file, use the timeout option on each individual test.
If you want to set the timeout for all test files, use testTimeout configuration option.