O Objeto 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'
.
Os exemplos de TypeScript desta página só funcionarão como documentados se você importar explicitamente APIs do Jest:
import {expect, jest, test} from '@jest/globals';
Consulte o guia Iniciando para obter detalhes sobre como configurar Jest com TypeScript.
Métodos
- Mock Modules
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)
- Funções de Simulação
- Fake Timers
jest.useFakeTimers(fakeTimersConfig?)
jest.useRealTimers()
jest.runAllTicks()
jest.runAllTimers()
jest.runAllImmediates()
jest.advanceTimersByTime(msToRun)
jest.runOnlyPendingTimers()
jest.advanceTimersToNextTimer(steps)
jest.clearAllTimers()
jest.getTimerCount()
jest.setSystemTime(now?: number | Date)
jest.getRealSystemTime()
- Misc
Mock Modules
jest.disableAutomock()
Desabilita simulações automáticas no carregador de módulo.
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');
});
Isto é geralmente útil quando você tiver um cenário onde o número de dependências que se quer simular (mock, em inglês) é muito menor do que o número de dependências que você não quer. Por exemplo, se você estiver escrevendo um teste para um módulo que utiliza um grande número de dependências que podem razoavelmente ser classificadas como "detalhes de implementação" do módulo, então você provavelmente não quer simular elas.
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
.
Retorna o objeto jest
para encadeamento.
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()
Habilita simulações automáticas no carregador de módulo.
For more details on automatic mocking see documentation of automock
configuration option.
Example:
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();
});
Retorna o objeto jest
para encadeamento.
Ao usar babel-jest
, chamadas para enableAutomock
serão automaticamente içadas (hoisted, em inglês) até o topo do bloco de código. Use autoMockOn
se você quiser evitar explicitamente esse comportamento.
jest.createMockFromModule(moduleName)
Dado o nome de um módulo, use o sistema automático de simulação para gerar uma versão simulada do módulo para você.
This is useful when you want to create a manual mock that extends the automatic mock's behavior:
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);
});
This is how createMockFromModule
will mock the following data types:
Funções
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
Creates a new class. The interface of the original class is maintained, all of the class member functions and properties will be mocked.
Object
Creates a new deeply cloned object. The object keys are maintained and their values are mocked.
Array
Creates a new empty array, ignoring the original.
Primitives
Creates a new property with the same primitive value as the original property.
Example:
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)
Simula um módulo com uma versão auto simulada quando ele está sendo "required". factory
e options
são opcionais. Por exemplo:
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.
O segundo argumento pode ser usado para especificar um módulo factory explícito que está sendo executado em vez de usar o recurso de automocking do Jest:
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';
When using the factory
parameter for an ES6 module with a default export, the __esModule: true
property needs to be specified. This property is normally generated by Babel / TypeScript, but here it needs to be set manually. 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
O terceiro argumento pode ser usado para criar simulações virtuais – simulações de módulos que não existem em qualquer lugar no sistema:
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.
Módulos que são simulados (mocked, em inglês) com jest.mock
são simulados apenas para o arquivo que chama jest.mock
. Another file that imports the module will get the original implementation even if it runs after the test file that mocks the module.
Retorna o objeto jest
para encadeamento.
Writing tests in 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)
Indica que o sistema de módulo nunca deve retornar uma versão simulada (mocked, em inglês) do módulo especificado no require()
(por exemplo, que ele sempre deve retornar o módulo real).
O uso mais comum dessa API é para especificar ao módulo que um determinado teste pretende testar (e, portanto, não quer ser automaticamente simulado).
Retorna o objeto jest
para encadeamento.
jest.deepUnmock(moduleName)
Indicates that the module system should never return a mocked version of the specified module and its dependencies.
Retorna o objeto jest
para encadeamento.
jest.doMock(moduleName, factory, options)
Ao usar babel-jest
, chamadas para mock
serão automaticamente içadas (hoisted, em inglês) até o topo do bloco de código. Use este método se você deseja evitar explicitamente esse comportamento.
Um exemplo de quando isso é útil é quando você quer simular (mock, em inglês) de outra maneira um módulo dentro do mesmo arquivo:
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);
});
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: true
property (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()
. - Finally, we need an environment which supports dynamic importing. 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');
});
});
Retorna o objeto jest
para encadeamento.
jest.dontMock(moduleName)
Ao usar babel-jest
, chamadas para unmock
serão automaticamente içadas (hoisted, em inglês) até o topo do bloco de código. Use este método se você deseja evitar explicitamente esse comportamento.
Retorna o objeto jest
para encadeamento.
jest.setMock(moduleName, moduleExports)
Explicitamente fornece o objeto simulado (mock, em inglês) que o sistema de módulo deve retornar para o módulo especificado.
On occasion, there are times where the automatically generated mock the module system would normally provide you isn't adequate enough for your testing needs. Normalmente nessas circunstâncias você deve escrever uma simulação manual que for mais adequada para o módulo em questão. No entanto, em ocasiões extremamente raras, até mesmo um simulação manual não é apropriada para seus propósitos e você precisa construir a simulação você mesmo dentro de seu teste.
Nessas situações raras, você pode usar essa API para preencher manualmente o slot do registro "mock-module" no sistema do módulo.
Retorna o objeto jest
para encadeamento.
It is recommended to use jest.mock()
instead. O segundo argumento da API jest.mock
é uma fábrica de módulo, em vez do esperado objeto do módulo exportado.
jest.requireActual(moduleName)
Returns the actual module instead of a mock, bypassing all checks on whether the module should receive a mock implementation or not.
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.requireMock(moduleName)
Returns a mock module instead of the actual module, bypassing all checks on whether the module should be required normally or not.
jest.resetModules()
Redefine o registro do módulo - o cache de todos os módulos necessários. Isso é útil para isolar módulos onde o estado local pode entrar em conflito entre os testes.
Example:
const sum1 = require('../sum');
jest.resetModules();
const sum2 = require('../sum');
sum1 === sum2;
// > false (Both sum modules are separate "instances" of the sum module.)
Exemplo em um teste:
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.
});
Retorna o objeto jest
para encadeamento.
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. This is useful to isolate specific modules for every test so that local module state doesn't conflict between tests.
let myModule;
jest.isolateModules(() => {
myModule = require('myModule');
});
const otherCopyOfMyModule = require('myModule');
Funções de Simulação
jest.fn(implementation?)
Retorna uma nova, não utilizada função de simulação. Opcionalmente, toma uma implementação de simulação (mock, em inglês).
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)
Determina se a função dada é uma função simulada.
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. Este é um comportamento diferente da maioria das outras bibliotecas de teste. Se você deseja substituir a função original, você pode usar jest.spyOn(object, methodName).mockImplementation(() => customImplementation)
ou 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.
Example:
const video = {
play() {
return true;
},
};
module.exports = video;
Exemplo do teste:
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.
Example:
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;
Exemplo do teste:
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.clearAllMocks()
Clears the mock.calls
, mock.instances
, mock.contexts
and mock.results
properties of all mocks. Equivalent to calling .mockClear()
on every mocked function.
Retorna o objeto jest
para encadeamento.
jest.resetAllMocks()
Resets the state of all mocks. Equivalent to calling .mockReset()
on every mocked function.
Retorna o objeto jest
para encadeamento.
jest.restoreAllMocks()
Restaura todas as simulações (mocks, em inglês) para seu valor original. Equivalent to calling .mockRestore()
on every mocked function. Beware that jest.restoreAllMocks()
only works when the mock was created with jest.spyOn
; other mocks will require you to manually restore them.
Fake Timers
jest.useFakeTimers(fakeTimersConfig?)
Instructs Jest to use fake versions of the global date, performance, time and timer APIs. 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.
Configuration options:
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. 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();
// ...
});
For some reason you might have to use legacy implementation of fake timers. It can be enabled like this (additional options are not supported):
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.
Retorna o objeto jest
para encadeamento.
jest.useRealTimers()
Instructs Jest to restore the original implementations of the global date, performance, time and timer APIs. 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', () => {
// ...
});
Retorna o objeto jest
para encadeamento.
jest.runAllTicks()
Esgota a pilha de micro-task (geralmente usando um interface node via process.nextTick
).
Quando esta API for chamada, todas micro-tasks pendentes que foram empilhadas via process.nextTick
serão executadas. Adicionalmente, caso estas micro-tasks agendem novas micro-tasks, essas por sua vez serão esgotadas até que não haja mais micro-tasks na fila.
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
).
When this API is called, all pending macro-tasks and micro-tasks will be executed. If those tasks themselves schedule new tasks, those will be continually exhausted until there are no more tasks remaining in the queue.
Isso muitas vezes é útil para executar de modo síncrono setTimeouts durante um teste para verificar sincronicamente algum comportamento que só aconteceria após as "callbacks" setTimeout()
ou setInterval()
executarem. Consulte a documentação Simulações de Temporizador para obter mais informações.
jest.runAllImmediates()
Esgota todas as tarefas enfileiradas por setImmediate()
.
This function is only available when using legacy fake timers implementation.
jest.advanceTimersByTime(msToRun)
Executa somente a fila de tarefas macro (ou seja, todas as tarefas enfileiradas por setTimeout()
ou setInterval()
e 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.runOnlyPendingTimers()
Executa somente as macro-tasks que estão atualmente pendentes (ou seja, apenas as tarefas que foram enfileiradas por setTimeout()
ou setInterval()
até este ponto). Se qualquer uma das macro-tasks atualmente pendentes agendar novas macro-tasks, essas novas tarefas não serão executadas por essa chamada.
Isso é útil para cenários como aquele onde o módulo sendo testado agendará um setTimeout()
cuja "callback" agenda outro setTimeout()
recursivamente (ou seja, o agendamento nunca para). Nesses cenários, é útil ser capaz de executar para a frente no tempo, um passo de cada vez.
jest.advanceTimersToNextTimer(steps)
Advances all timers by the needed milliseconds so that only the next timeouts/intervals will run.
Optionally, you can provide steps
, so it will run steps
amount of next timeouts/intervals.
jest.clearAllTimers()
Remove quaisquer temporizadores pendentes do sistema de temporizador.
Isto significa que se quaisquer temporizadores foram programados (mas ainda não foram executados), eles serão apagados e nunca terão a oportunidade de executar no futuro.
jest.getTimerCount()
Returns the number of fake timers still left to run.
jest.setSystemTime(now?: number | Date)
Set the current system time used by fake timers. Simulates a user changing the system clock while your program is running. 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()
.
This function is not available when using legacy fake timers implementation.
jest.getRealSystemTime()
When mocking time, Date.now()
will also be mocked. If you for some reason need access to the real current time, you can invoke this function.
This function is not available when using legacy fake timers implementation.
Misc
jest.retryTimes(numRetries, options?)
Runs failed tests n-times until they pass or until the max number of retries is exhausted.
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);
});
Retorna o objeto jest
para encadeamento.
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)
Set the default timeout interval (in milliseconds) for all tests and before/after hooks in the test file. This only affects the test file from which this function is called. The default timeout interval is 5 seconds if this method is not called.
Example:
jest.setTimeout(1000); // 1 segundo
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.