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. Puteți crea o funcţie mock cu jest.fn()
. În cazul în care nu este specificată o implementare, funcţia mock va returna undefined
când este apelată.
Metode
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)
jest.MockedFunction
jest.MockedClass
Referințe
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 type
property, and a value
property. type
will be one of the following:
'return'
- Indicates that the call completed by returning normally.'throw'
- Indicates that the call completed by throwing a value.'incomplete'
- Indicates that the call has not yet completed. This occurs if you test the result from within the mock function itself, or from within a function that was called by the 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
Un array care conţine toate instanţele obiectelor instanţiate din această funcţie mock, folosind new
.
De exemplu: O funcţie mock, care a fost instanţiată de două ori ar avea array-ul mock.instances
următor:
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()
Resetează toate informaţiile stocate în array-urile mockFn.mock.calls
şi mockFn.mock.instances
.
Acest lucru este util atunci când doriţi să curăţați datele unui mock între două aserțiuni.
Țineți cont că mockClear
va înlocui mockFn.mock
, nu doar mockFn.mock.calls
şi 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.
Opţiunea de configurare clearMocks
este disponibilă pentru a curăța automat mock-urile între teste.
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).
Țineți cont că mockReset
va înlocui mockFn.mock
, nu doar mockFn.mock.calls
şi 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.
Acest lucru este util atunci când vreți să dublați funcţii în anumite cazuri de testare şi să restabiliți implementarea originală în altele.
Beware that mockFn.mockRestore
only works when the mock was created with jest.spyOn
. Așadar trebuie să faceți voi curățarea atunci când folosiți jest.fn()
.
The restoreMocks
configuration option is available to restore mocks automatically between tests.
mockFn.mockImplementation(fn)
Acceptă o funcţie care va fi folosită ca implementare a mock-ului. Mock în sine va înregistra în continuare toate apelurile și instanțierile – singura diferenţă este că implementarea va fi executată și ea când este apelat mock-ul.
Notă: jest.fn(implementare)
este o prescurtare pentru jest.fn().mockImplementation(implementare)
.
De exemplu:
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
poate fi folosit și pentru dublarea constructorilor 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)
Acceptă o funcţie care va fi utilizată ca implementare a mock-ului pentru un singur apel. Poate fi înlănțuită astfel încât mai multe apelări succesive vor produce rezultate diferite.
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
Atunci când funcţia mock rămâne fără implementări definite cu mockImplementationOnce, se va executa implementarea implicită cu jest.fn(() = > valoare-implicită)
sau .mockImplementation(() = > valoare-implicită)
dacă acestea au fost definite:
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.
De exemplu:
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)
Acceptă o valoare ce va fi returnată ori de câte ori se apelează funcţia mock.
const mock = jest.fn();
mock.mockReturnValue(42);
mock(); // 42
mock.mockReturnValue(43);
mock(); // 43
mockFn.mockReturnValueOnce(value)
Acceptă o valoare ce va fi returnată pentru un singur apel al funcţiei mock. Poate fi înlănțuită astfel încât apeluri succesive ale funcţiei mock vor returna valori diferite. Atunci când nu mai există valori mockReturnValueOnce
rămase, apelurile următoare vor returna valoarea specificată de 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"
});
TypeScript
Jest itself is written in TypeScript.
If you are using Create React App then the TypeScript template has everything you need to start writing tests in TypeScript.
Otherwise, please see our Getting Started guide for to get setup with TypeScript.
You can see an example of using Jest with TypeScript in our GitHub repository.
jest.MockedFunction
jest.MockedFunction
is available in the@types/jest
module from version24.9.0
.
The following examples will assume you have an understanding of how Jest mock functions work with JavaScript.
You can use jest.MockedFunction
to represent a function that has been replaced by a Jest mock.
Example using automatic jest.mock
:
// Assume `add` is imported and used within `calculate`.
import add from './add';
import calculate from './calc';
jest.mock('./add');
// Our mock of `add` is now fully typed
const mockAdd = add as jest.MockedFunction<typeof add>;
test('calculate calls add', () => {
calculate('Add', 1, 2);
expect(mockAdd).toBeCalledTimes(1);
expect(mockAdd).toBeCalledWith(1, 2);
});
Example using jest.fn
:
// Here `add` is imported for its type
import add from './add';
import calculate from './calc';
test('calculate calls add', () => {
// Create a new mock that can be used in place of `add`.
const mockAdd = jest.fn() as jest.MockedFunction<typeof add>;
// Note: You can use the `jest.fn` type directly like this if you want:
// const mockAdd = jest.fn<ReturnType<typeof add>, Parameters<typeof add>>();
// `jest.MockedFunction` is a more friendly shortcut.
// Now we can easily set up mock implementations.
// All the `.mock*` API can now give you proper types for `add`.
// https://jestjs.io/docs/en/mock-function-api
// `.mockImplementation` can now infer that `a` and `b` are `number`
// and that the returned value is a `number`.
mockAdd.mockImplementation((a, b) => {
// Yes, this mock is still adding two numbers but imagine this
// was a complex function we are mocking.
return a + b
}));
// `mockAdd` is properly typed and therefore accepted by
// anything requiring `add`.
calculate(mockAdd, 1 , 2);
expect(mockAdd).toBeCalledTimes(1);
expect(mockAdd).toBeCalledWith(1, 2);
})
jest.MockedClass
jest.MockedClass
is available in the@types/jest
module from version24.9.0
.
The following examples will assume you have an understanding of how Jest mock classes work with JavaScript.
You can use jest.MockedClass
to represent a class that has been replaced by a Jest mock.
Converting the ES6 Class automatic mock example would look like this:
import SoundPlayer from '../sound-player';
import SoundPlayerConsumer from '../sound-player-consumer';
jest.mock('../sound-player'); // SoundPlayer is now a mock constructor
const SoundPlayerMock = SoundPlayer as jest.MockedClass<typeof SoundPlayer>;
beforeEach(() => {
// Clear all instances and calls to constructor and all methods:
SoundPlayerMock.mockClear();
});
it('We can check if the consumer called the class constructor', () => {
const soundPlayerConsumer = new SoundPlayerConsumer();
expect(SoundPlayerMock).toHaveBeenCalledTimes(1);
});
it('We can check if the consumer called a method on the class instance', () => {
// Show that mockClear() is working:
expect(SoundPlayerMock).not.toHaveBeenCalled();
const soundPlayerConsumer = new SoundPlayerConsumer();
// Constructor should have been called again:
expect(SoundPlayerMock).toHaveBeenCalledTimes(1);
const coolSoundFileName = 'song.mp3';
soundPlayerConsumer.playSomethingCool();
// mock.instances is available with automatic mocks:
const mockSoundPlayerInstance = SoundPlayerMock.mock.instances[0];
// However, it will not allow access to `.mock` in TypeScript as it
// is returning `SoundPlayer`. Instead, you can check the calls to a
// method like this fully typed:
expect(SoundPlayerMock.prototype.playSoundFile.mock.calls[0][0]).toEqual(
coolSoundFileName,
);
// Equivalent to above check:
expect(SoundPlayerMock.prototype.playSoundFile).toHaveBeenCalledWith(
coolSoundFileName,
);
expect(SoundPlayerMock.prototype.playSoundFile).toHaveBeenCalledTimes(1);
});