Skip to main content
Version: 26.x

El 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'.

Métodos


Mock Modules

jest.disableAutomock()

Deshabilita la simulación mock automática en el cargador de módulos.

info

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.

Jest configuration:

{
"automock": true
}

Ejemplo:

utils.js
export default {
authorize: () => {
return 'token';
},
};
__tests__/disableAutomocking.js
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');
});

Esto es especialmente útil en el caso donde las dependencias que se desean simular es mucho menor a las dependencias que no se desean simular. Por ejemplo, si se escribe un test para un módulo que ocupa una gran cantidad de dependencias que se podrían clasificar como "detalles de la implementación", es probable que no se deseen simular.

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.

Regresa el objeto jest para poder ser usado llamadas consecutivas.

tip

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 la simulación mock automática en el cargador de módulos.

info

For more details on automatic mocking see documentation of automock configuration option.

Ejemplo:

utils.js
export default {
authorize: () => {
return 'token';
},
isAuthorized: secret => secret === 'wizard',
};
__tests__/enableAutomocking.js
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();
});

Regresa el objeto jest para poder ser usado llamadas consecutivas.

tip

Cuando se usa babel-jest, las llamadas a enableAutomock se llevan automáticamente al principio del bloque de código. Si se desea evitar este comportamiento, se debe usar autoMockOn.

jest.createMockFromModule(moduleName)

tip

Renamed from .genMockFromModule(moduleName) in Jest 26.

Dado el nombre de un modulo, usa el sistema automático de simulación mock para generar una versión mock del modulo deseado.

Esto es útil cuando se desea crear una simulación manual que extiende el comportamiento automático de la simulación mock.

Ejemplo:

utils.js
module.exports = {
authorize: () => {
return 'token';
},
isAuthorized: secret => secret === 'wizard',
};
__tests__/createMockFromModule.test.js
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:

Funciones

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.

Objeto

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.

Ejemplo:

example.js
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'),
};
__tests__/example.test.js
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)

Crea una simulación mock de un modulo auto-mocked cuando es requerido. Las opciones factory y options son opcionales. Por ejemplo:

banana.js
module.exports = () => 'banana';
__tests__/test.js
jest.mock('../banana');

const banana = require('../banana'); // banana will be explicitly mocked.

banana(); // will return 'undefined' because the function is auto-mocked.

El segundo argumento puede usarse para especificar que se ejecute una fábrica de módulos de manera explicita en lugar de la funcionalidad de simulación mock automática de 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

El tercer argumento puede ser usado para crear simulaciones mock virtuales, es decir, mocks de módulos que no existen en ninguna parte del 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},
);
caution

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.

Los módulos que son simulados vía jest.mock son solo simulados para el archivo que ejecuta 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.

Regresa el objeto jest para poder ser usado llamadas consecutivas.

jest.unmock(moduleName)

Le indica al sistema de módulos que nunca debe regresar una versión simulada mock de un modulo en especifico cuando se importe vía require() (es decir, que siempre debe regresar el modulo real).

El uso más común de esta API es para especificar el modulo que se va a probar (y que por tanto no se desea simular automáticamente).

Regresa el objeto jest para poder ser usado llamadas consecutivas.

jest.deepUnmock(moduleName)

Indicates that the module system should never return a mocked version of the specified module and its dependencies.

Regresa el objeto jest para poder ser usado llamadas consecutivas.

jest.doMock(moduleName, factory, options)

When using babel-jest, calls to mock will automatically be hoisted to the top of the code block. Use this method if you want to explicitly avoid this behavior.

Un ejemplo cuando esto es util es cuando desea simular un modulo de manera diferente dentro del mismo archivo:

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 the jest.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');
});
});

Regresa el objeto jest para poder ser usado llamadas consecutivas.

jest.dontMock(moduleName)

Cuando se usa babel-jest, las llamadas a unmock se llevan automáticamente al principio del bloque de código. Use this method if you want to explicitly avoid this behavior.

Regresa el objeto jest para poder ser usado llamadas consecutivas.

jest.setMock(moduleName, moduleExports)

Provee de manera especifica el modulo simulado mock que el sistema de módulos debe regresar para un modulo en especifico.

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, en esas circunstancias se debe escribir un módulo mock manual que sea más adecuado para el módulo en cuestión. Y sin embargo, en raras ocasiones, inclusive un mock manual puede no ser apropiado para los propósitos de la prueba, en cuyo caso se tiene que construir el mock dentro de la prueba.

En estos raros casos, se puede ocupar esta API para llenar de manera manual el registro del módulo mock en el sistema de módulos.

Regresa el objeto jest para poder ser usado llamadas consecutivas.

info

It is recommended to use jest.mock() instead. El segundo argumento del API de jest.mock es una fábrica de modulos en lugar del objeto del modulo que se espera exportar.

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.

Ejemplo:

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().mockReturnValue(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()

Restablece el registro de módulos - el caché de todos los módulos importados. Esto es útil para aislar módulos donde estado local podría entrar en conflicto entre pruebas.

Ejemplo:

const sum1 = require('../sum');
jest.resetModules();
const sum2 = require('../sum');
sum1 === sum2;
// > false (Both sum modules are separate "instances" of the sum module.)

Ejemplo en una prueba:

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.
});

Regresa el objeto jest para poder ser usado llamadas consecutivas.

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');

Funciones Mock

jest.fn(implementation?)

Regresa una nueva instancia, sin utilizar, de una función mock. Opcionalmente acepta como parámetro una implementación de mock.

const mockFn = jest.fn();
mockFn();
expect(mockFn).toHaveBeenCalled();

// With a mock implementation:
const returnsTrue = jest.fn(() => true);
console.log(returnsTrue()); // true;

jest.isMockFunction(fn)

Determina si la función dada es una función 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.

note

By default, jest.spyOn also calls the spied method. Este comportamiento es diferente de casi todas las otras librerías para pruebas. Si se desea remplazar la función original, se puede usar jest.spyOn(object, methodName).mockImplementation(() => implementacionPropia) o object[methodName] = jest.fn(() => implementacionPropia);

tip

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.

Ejemplo:

const video = {
play() {
return true;
},
};

module.exports = video;

Prueba de ejemplo:

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.

Ejemplo:

const video = {
// it's a getter!
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;
set volume(value) {
this._volume = value;
},
get volume() {
return this._volume;
},
};

module.exports = audio;

Prueba de ejemplo:

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 and mock.results properties of all mocks. Equivalent to calling .mockClear() on every mocked function.

Regresa el objeto jest para poder ser usado llamadas consecutivas.

jest.resetAllMocks()

Resets the state of all mocks. Equivalent to calling .mockReset() on every mocked function.

Regresa el objeto jest para poder ser usado llamadas consecutivas.

jest.restoreAllMocks()

Restaura todos los objetos duplicados a su 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.

Mock Timers

jest.useFakeTimers(implementation?: 'modern' | 'legacy')

Instructs Jest to use fake versions of the standard timer functions (setTimeout, setInterval, clearTimeout, clearInterval, nextTick, setImmediate and clearImmediate as well as Date).

If you pass 'legacy' as an argument, Jest's legacy implementation will be used rather than one based on @sinonjs/fake-timers. This also mocks additional timers like Date. 'modern' will be the default behavior in Jest 27.

Regresa el objeto jest para poder ser usado llamadas consecutivas.

jest.useRealTimers()

Indica a Jest que se deben ocupar las versiones reales de las funciones estándares de temporizadores.

Regresa el objeto jest para poder ser usado llamadas consecutivas.

jest.runAllTicks()

Agota la cola de tareas micro (cuya interfaz en node es process.nextTick).

Cuando se llama a este API, todas las micro-tareas que estén en la cola de process.nextTick serán ejecutadas. De manera adicional, si esas micro-tareas mismas crean nuevas micro-tareas, éstas se agotaran continuamente hasta que no haya más micro-tareas en la cola.

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.

Esto es útil para ejecutar setTimeouts de manera sincronía en una prueba para así verificar de manera sincronía acciones que ocurrirían después de que se ejecuten los callbacks de setTimeout() o setInterval(). Véase el documento de Simulaciones de temporizadores para más información.

jest.runAllImmediates()

Agota todas las tareas en la cola de setImmediate().

info

This function is not available when using modern fake timers implementation.

jest.advanceTimersByTime(msToRun)

Ejecuta solo las tareas macro (es decir todas aquellas programadas por setTimeout(), setInterval() y setImmediate()).

Cuando este API es llamado, todos los timers son avanzados por milisegundos msToRun. 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()

Ejecuta solo las macro-tareas que se encuentren pendientes (es decir, sólo las tareas que entraron a la cola vía setTimeout() o setInterval() hasta ese momento). Si cualquiera de esas macro-tareas crearon nuevas macro-tareas, éstas últimas no se ejecutarán en esta llamada.

Esto es útil para escenarios donde el modulo probado llama a setTimeout() y éste a su vez llama a setTimeout() de manera recursiva (de manera que las llamadas nunca terminan). En dichos escenarios, es útil poder avanzar en la linea de tiempo de ejecución un paso a la 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()

Remueve cualquier temporizador pendiente en el sistema de temporizadores.

Esto significa que, cualquier temporizador que haya sido programado (pero no se ha ejecutado aún), será borrado y no tendrá la oportunidad de ejecutarse en un 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().

info

This function is only available when using modern 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.

info

This function is only available when using modern 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);
});

Regresa el objeto jest para poder ser usado llamadas consecutivas.

caution

jest.retryTimes() must be declared at the top level of a test file or in a describe block.

info

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.

Ejemplo:

jest.setTimeout(1000); // 1 second
tip

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.