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)
jest.isolateModulesAsync(fn)
- Funções de Simulação
- Fake Timers
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()
- 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:
- 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:
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:
- 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. 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.