Mock-функции
Mock-функции также известны как "шпионы", потому что они позволяют вам шпионить за поведением функции, которая вызывается косвенно каким-либо другим кодом, а не только тестировать вывод. Mock-функцию можно создать при помощи jest.fn()
. Если реализация не задана, то при вызове mock-функция вернет значение undefined
.
Примеры TypeScript с этой страницы будут работать только в том случае, если вы явно импортируете Jest API:
Import {expect, jest, test} from '@jest/globals';
Обратитесь к Началу работы за подробностями о том, как установить Jest с TypeScript.
Методы
- Справка
mockFn.getMockName()
mockFn.mock.calls
mockFn.mock.results
mockFn.mock.instances
mockFn.mock.contexts
mockFn.mock.lastCall
mockFn.mockClear()
mockFn.mockReset()
mockFn.mockRestore()
mockFn.mockImplementation(fn)
mockFn.mockImplementationOnce(fn)
mockFn.mockName(name)
mockFn.mockReturnThis()
mockFn.mockReturnValue(value)
mockFn.mockReturnValueOnce(value)
mockFn.mockResolvedValue(value)
mockFn.mockResolvedValueOnce(value)
mockFn.mockRejectedValue(value)
mockFn.mockRejectedValueOnce(value)
mockFn.withImplementation(fn, callback)
- Replaced Properties
- TypeScript Usage
Справка
mockFn.getMockName()
Возвращает набор имён mock-фукнции путем вызова .mockName()
.
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 type
property, and a value
property. type
will be one of the following:
'return'
- указывает, что вызов завершился корректно.'throw'
- указывает, что вызов завершился путем выброса исключения.'incomplete'
- указывает, что вызов еще не завершен. Это происходит, если вы протестируете результат внутри самой mock-функции или из функции, вызванной mock-функ цией.
The value
property contains the value that was thrown or returned. value
is undefined when type === 'incomplete'
.
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:
[
{
type: 'return',
value: 'result1',
},
{
type: 'throw',
value: {
/* Error instance */
},
},
{
type: 'return',
value: 'result2',
},
];
mockFn.mock.instances
An array that contains all the object instances that have been instantiated from this mock function using new
.
For example: A mock function that has been instantiated twice would have the following mock.instances
array:
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.mock.contexts
An array that contains the contexts for all calls of the mock function.
A context is the this
value that a function receives when called. The context can be set using Function.prototype.bind
, Function.prototype.call
or Function.prototype.apply
.
Например:
const mockFn = jest.fn();
const boundMockFn = mockFn.bind(thisContext0);
boundMockFn('a', 'b');
mockFn.call(thisContext1, 'a', 'b');
mockFn.apply(thisContext2, ['a', 'b']);
mockFn.mock.contexts[0] === thisContext0; // true
mockFn.mock.contexts[1] === thisContext1; // true
mockFn.mock.contexts[2] === thisContext2; // true
mockFn.mock.lastCall
An array containing the call arguments of the last call that was made to this mock function. If the function was not called, it will return undefined
.
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.lastCall
array that looks like this:
['arg3', 'arg4'];
mockFn.mockClear()
Clears all information stored in the mockFn.mock.calls
, mockFn.mock.instances
, mockFn.mock.contexts
and mockFn.mock.results
arrays. Often this is useful when you want to clean up a mocks usage data between two assertions.
The clearMocks
configuration option is available to clear mocks automatically before each tests.
Beware that mockFn.mockClear()
will replace mockFn.mock
, not just reset the values of its properties! You should, therefore, avoid assigning mockFn.mock
to other variables, temporary or not, to make sure you don't access stale data.
mockFn.mockReset()
Does everything that mockFn.mockClear()
does, and also replaces the mock implementation with an empty function, returning undefined
.
The resetMocks
configuration option is available to reset mocks automatically before each test.
mockFn.mockRestore()
Does everything that mockFn.mockReset()
does, and also restores the original (non-mocked) implementation.
This is useful when you want to mock functions in certain test cases and restore the original implementation in others.
The restoreMocks
configuration option is available to restore mocks automatically before each test.
mockFn.mockRestore()
only works when the mock was created with jest.spyOn()
. Thus you have to take care of restoration yourself when manually assigning jest.fn()
.
mockFn.mockImplementation(fn)
Accepts a function that should be used as the implementation of the mock. The mock itself will still record all calls that go into and instances that come from itself – the only difference is that the implementation will also be executed when the mock is called.
jest.fn(implementation)
is a shorthand for jest.fn().mockImplementation(implementation)
.
- JavaScript
- TypeScript
const mockFn = jest.fn(scalar => 42 + scalar);
mockFn(0); // 42
mockFn(1); // 43
mockFn.mockImplementation(scalar => 36 + scalar);
mockFn(2); // 38
mockFn(3); // 39
import {jest} from '@jest/globals';
const mockFn = jest.fn((scalar: number) => 42 + scalar);
mockFn(0); // 42
mockFn(1); // 43
mockFn.mockImplementation(scalar => 36 + scalar);
mockFn(2); // 38
mockFn(3); // 39
.mockImplementation()
can also be used to mock class constructors:
- JavaScript
- TypeScript
module.exports = class SomeClass {
method(a, b) {}
};
const SomeClass = require('./SomeClass');
jest.mock('./SomeClass'); // this happens automatically with automocking
const mockMethod = jest.fn();
SomeClass.mockImplementation(() => {
return {
method: mockMethod,
};
});
const some = new SomeClass();
some.method('a', 'b');
console.log('Calls to method:', mockMethod.mock.calls);
export class SomeClass {
method(a: string, b: string): void {}
}
import {jest} from '@jest/globals';
import {SomeClass} from './SomeClass';
jest.mock('./SomeClass'); // this happens automatically with automocking
const mockMethod = jest.fn<(a: string, b: string) => void>();
jest.mocked(SomeClass).mockImplementation(() => {
return {
method: mockMethod,
};
});
const some = new SomeClass();
some.method('a', 'b');
console.log('Calls to method:', mockMethod.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.
- JavaScript
- TypeScript
const mockFn = jest
.fn()
.mockImplementationOnce(cb => cb(null, true))
.mockImplementationOnce(cb => cb(null, false));
mockFn((err, val) => console.log(val)); // true
mockFn((err, val) => console.log(val)); // false
import {jest} from '@jest/globals';
const mockFn = jest
.fn<(cb: (a: null, b: boolean) => void) => void>()
.mockImplementationOnce(cb => cb(null, true))
.mockImplementationOnce(cb => cb(null, false));
mockFn((err, val) => console.log(val)); // true
mockFn((err, val) => console.log(val)); // false