Mock Functions
Mock functions are also known as "spies", because they let you spy on the behavior of a function that is called indirectly by some other code, rather than only testing the output. Puedes crear una falsa función con jest.fn()
. Si no se da la implementación, la función mockeda devolverá undefined
cuando se invoque.
Métodos
mockFn.getMockName()
mockFn.mock.calls
mockFn.mock.results
mockFn.mock.instances
mockFn.mockClear()
mockFn.mockReset()
mockFn.mockRestore()
mockFn.mockImplementation(fn)
mockFn.mockImplementationOnce(fn)
mockFn.mockName(value)
mockFn.mockReturnThis()
mockFn.mockReturnValue(value)
mockFn.mockReturnValueOnce(value)
mockFn.mockResolvedValue(value)
mockFn.mockResolvedValueOnce(value)
mockFn.mockRejectedValue(value)
mockFn.mockRejectedValueOnce(value)
Referencia
mockFn.getMockName()
Returns the mock name string set by calling mockFn.mockName(value)
.
mockFn.mock.calls
An array containing the call arguments of all calls that have been made to this mock function. Each item in the array is an array of arguments that were passed during the call.
For example: A mock function f
that has been called twice, with the arguments f('arg1', 'arg2')
, and then with the arguments f('arg3', 'arg4')
, would have a mock.calls
array that looks like this:
[
['arg1', 'arg2'],
['arg3', 'arg4'],
];
mockFn.mock.results
An array containing the results of all calls that have been made to this mock function. Each entry in this array is an object containing a boolean isThrow
property, and a value
property. isThrow
is true if the call terminated due to a throw
, or false if the call returned normally. The value
property contains the value that was thrown or returned.
For example: A mock function f
that has been called three times, returning result1
, throwing an error, and then returning result2
, would have a mock.results
array that looks like this:
[
{
isThrow: false,
value: 'result1',
},
{
isThrow: true,
value: {
/* Error instance */
},
},
{
isThrow: false,
value: 'result2',
},
];
mockFn.mock.instances
Una matriz que contiene todas las instancias de objeto que han se han creado instancias de esta función mockeada utilizando new
.
Por ejemplo: una función mockeada que ha creado una instancia dos veces, tendría la siguiente matriz de mock.instances
:
const mockFn = jest.fn();
const a = new mockFn();
const b = new mockFn();
mockFn.mock.instances[0] === a; // true
mockFn.mock.instances[1] === b; // true
mockFn.mockClear()
Restablece toda la información almacenada en las matrices mockFn.mock.calls
y mockFn.mock.instances
.
A menudo esto es útil cuando quieres limpiar datos de uso de mocking entre dos afirmaciones.
Cuidado con ese mockClear
reemplazará a mockFn.mock
, no mockFn.mock.calls
y mockFn.mock.instances
. You should, therefore, avoid assigning mockFn.mock
to other variables, temporary or not, to make sure you don't access stale data.
The clearMocks
configuration option is available to clear mocks automatically between tests.
mockFn.mockReset()
Does everything that mockFn.mockClear()
does, and also removes any mocked return values or implementations.
This is useful when you want to completely reset a mock back to its initial state. (Note that resetting a spy will result in a function with no return value).
Cuidado con ese mockClear
reemplazará a mockFn.mock
, no mockFn.mock.calls
y mockFn.mock.instances
. You should, therefore, avoid assigning mockFn.mock
to other variables, temporary or not, to make sure you don't access stale data.
mockFn.mockRestore()
Does everything that mockFn.mockReset()
does, and also restores the original (non-mocked) implementation.
Esto es útil para casos donde se desee simular funciones en ciertas pruebas y restaurar la implementación original para otras.
Beware that mockFn.mockRestore
only works when the mock was created with jest.spyOn
. De modo que se debe realizar la restauración de manera independiente a Jest cuando se crean mocks con jest.fn()
.
The restoreMocks
configuration option is available to restore mocks automatically between tests.
mockFn.mockImplementation(fn)
Acepta una función que debe ser utilizada como la implementación de la funcion a mockear. El mockeo de sí mismo aún grabará todas las llamadas que entran y casos que provienen de sí mismo, la única diferencia es que la aplicación también se ejecutará cuando se llama a la funcion mock.
Note: jest.fn(implementation)
is a shorthand for jest.fn().mockImplementation(implementation)
.
Por ejemplo:
const mockFn = jest.fn().mockImplementation(scalar => 42 + scalar);
// or: jest.fn(scalar => 42 + scalar);
const a = mockFn(0);
const b = mockFn(1);
a === 42; // true
b === 43; // true
mockFn.mock.calls[0][0] === 0; // true
mockFn.mock.calls[1][0] === 1; // true
mockImplementation
puede utilizarse también para mockear constructores de clase:
// SomeClass.js
module.exports = class SomeClass {
m(a, b) {}
};
// OtherModule.test.js
jest.mock('./SomeClass'); // this happens automatically with automocking
const SomeClass = require('./SomeClass');
const mMock = jest.fn();
SomeClass.mockImplementation(() => {
return {
m: mMock,
};
});
const some = new SomeClass();
some.m('a', 'b');
console.log('Calls to m: ', mMock.mock.calls);
mockFn.mockImplementationOnce(fn)
Accepts a function that will be used as an implementation of the mock for one call to the mocked function. Can be chained so that multiple function calls produce different results.
const myMockFn = jest
.fn()
.mockImplementationOnce(cb => cb(null, true))
.mockImplementationOnce(cb => cb(null, false));
myMockFn((err, val) => console.log(val)); // true
myMockFn((err, val) => console.log(val)); // false
Cuando se ejecuta la función mockeada de implementaciones definidas con mockImplementationOnce, se ejecutará la aplicación por defecto con jest.fn(() = > defaultValue)
o .mockImplementation(() = > defaultValue)
si se llamara:
const myMockFn = jest
.fn(() => 'default')
.mockImplementationOnce(() => 'first call')
.mockImplementationOnce(() => 'second call');
// 'first call', 'second call', 'default', 'default'
console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn());
mockFn.mockName(value)
Accepts a string to use in test result output in place of "jest.fn()" to indicate which mock function is being referenced.
Por ejemplo:
const mockFn = jest.fn().mockName('mockedFunction');
// mockFn();
expect(mockFn).toHaveBeenCalled();
Will result in this error:
expect(mockedFunction).toHaveBeenCalled()
Expected mock function "mockedFunction" to have been called, but it was not called.
mockFn.mockReturnThis()
Syntactic sugar function for:
jest.fn(function () {
return this;
});
mockFn.mockReturnValue(value)
Accepts a value that will be returned whenever the mock function is called.
const mock = jest.fn();
mock.mockReturnValue(42);
mock(); // 42
mock.mockReturnValue(43);
mock(); // 43
mockFn.mockReturnValueOnce(value)
Acepta un valor que se devolverá para una llamada a la función de prueba. Can be chained so that successive calls to the mock function return different values. When there are no more mockReturnValueOnce
values to use, calls will return a value specified by mockReturnValue
.
const myMockFn = jest
.fn()
.mockReturnValue('default')
.mockReturnValueOnce('first call')
.mockReturnValueOnce('second call');
// 'first call', 'second call', 'default', 'default'
console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn());
mockFn.mockResolvedValue(value)
Syntactic sugar function for:
jest.fn().mockImplementation(() => Promise.resolve(value));
Useful to mock async functions in async tests:
test('async test', async () => {
const asyncMock = jest.fn().mockResolvedValue(43);
await asyncMock(); // 43
});
mockFn.mockResolvedValueOnce(value)
Syntactic sugar function for:
jest.fn().mockImplementationOnce(() => Promise.resolve(value));
Useful to resolve different values over multiple async calls:
test('async test', async () => {
const asyncMock = jest
.fn()
.mockResolvedValue('default')
.mockResolvedValueOnce('first call')
.mockResolvedValueOnce('second call');
await asyncMock(); // first call
await asyncMock(); // second call
await asyncMock(); // default
await asyncMock(); // default
});
mockFn.mockRejectedValue(value)
Syntactic sugar function for:
jest.fn().mockImplementation(() => Promise.reject(value));
Useful to create async mock functions that will always reject:
test('async test', async () => {
const asyncMock = jest.fn().mockRejectedValue(new Error('Async error'));
await asyncMock(); // throws "Async error"
});
mockFn.mockRejectedValueOnce(value)
Syntactic sugar function for:
jest.fn().mockImplementationOnce(() => Promise.reject(value));
Example usage:
test('async test', async () => {
const asyncMock = jest
.fn()
.mockResolvedValueOnce('first call')
.mockRejectedValueOnce(new Error('Async error'));
await asyncMock(); // first call
await asyncMock(); // throws "Async error"
});