模拟函数

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. You can create a mock function with jest.fn(). If no implementation is given, the mock function will return undefined when invoked. 你可以通过 jest.fn() 创建 mock 函数。 如果没有提供实现,调用模拟函数将返回 undefined

模拟函数 - 图1信息

The TypeScript examples from this page will only work as documented if you explicitly import Jest APIs:

  1. import {expect, jest, test} from '@jest/globals';

Consult the Getting Started guide for details on how to setup Jest with TypeScript.

方法


参考

mockFn.getMockName()

Returns the mock name string set by calling .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. 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:

  1. [
  2. ['arg1', 'arg2'],
  3. ['arg3', 'arg4'],
  4. ];

mockFn.mock.results

An array containing the results of all calls that have been made to this mock function. 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: 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. '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. 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:

  1. [
  2. {
  3. type: 'return',
  4. value: 'result1',
  5. },
  6. {
  7. type: 'throw',
  8. value: {
  9. /* Error instance */
  10. },
  11. },
  12. {
  13. type: 'return',
  14. value: 'result2',
  15. },
  16. ];

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:

  1. const mockFn = jest.fn();
  2. const a = new mockFn();
  3. const b = new mockFn();
  4. mockFn.mock.instances[0] === a; // true
  5. mockFn.mock.instances[1] === b; // true

mockFn.mock.contexts

一个包含mock函数所有调用上下文的数组。

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.

例如:

  1. const mockFn = jest.fn();
  2. const boundMockFn = mockFn.bind(thisContext0);
  3. boundMockFn('a', 'b');
  4. mockFn.call(thisContext1, 'a', 'b');
  5. mockFn.apply(thisContext2, ['a', 'b']);
  6. mockFn.mock.contexts[0] === thisContext0; // true
  7. mockFn.mock.contexts[1] === thisContext1; // true
  8. 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:

  1. ['arg3', 'arg4'];

mockFn.mockClear()

清空所有存储在mockFn.mock.calls, mockFn.mock.instances, mockFn.mock.contexts的信息和mockFn.mock.results 数组。 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.

模拟函数 - 图2注意

请注意, mockFn.mockClear()会替换掉 mockFn.mock,而不只是重置其属性的值! 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.

模拟函数 - 图3信息

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.

模拟函数 - 图4提示

jest.fn(implementation) is a shorthand for jest.fn().mockImplementation(implementation).

  • JavaScript
  • TypeScript
  1. const mockFn = jest.fn(scalar => 42 + scalar);
  2. mockFn(0); // 42
  3. mockFn(1); // 43
  4. mockFn.mockImplementation(scalar => 36 + scalar);
  5. mockFn(2); // 38
  6. mockFn(3); // 39
  1. import {jest} from '@jest/globals';
  2. const mockFn = jest.fn((scalar: number) => 42 + scalar);
  3. mockFn(0); // 42
  4. mockFn(1); // 43
  5. mockFn.mockImplementation(scalar => 36 + scalar);
  6. mockFn(2); // 38
  7. mockFn(3); // 39

.mockImplementation() 也可以用于模拟类构造器:

  • JavaScript
  • TypeScript

SomeClass.js

  1. module.exports = class SomeClass {
  2. method(a, b) {}
  3. };

SomeClass.test.js

  1. const SomeClass = require('./SomeClass');
  2. jest.mock('./SomeClass'); // this happens automatically with automocking
  3. const mockMethod = jest.fn();
  4. SomeClass.mockImplementation(() => {
  5. return {
  6. method: mockMethod,
  7. };
  8. });
  9. const some = new SomeClass();
  10. some.method('a', 'b');
  11. console.log('Calls to method:', mockMethod.mock.calls);

SomeClass.ts

  1. export class SomeClass {
  2. method(a: string, b: string): void {}
  3. }

SomeClass.test.ts

  1. import {jest} from '@jest/globals';
  2. import {SomeClass} from './SomeClass';
  3. jest.mock('./SomeClass'); // this happens automatically with automocking
  4. const mockMethod = jest.fn<(a: string, b: string) => void>();
  5. jest.mocked(SomeClass).mockImplementation(() => {
  6. return {
  7. method: mockMethod,
  8. };
  9. });
  10. const some = new SomeClass();
  11. some.method('a', 'b');
  12. 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. Can be chained so that multiple function calls produce different results.

  • JavaScript
  • TypeScript
  1. const mockFn = jest
  2. .fn()
  3. .mockImplementationOnce(cb => cb(null, true))
  4. .mockImplementationOnce(cb => cb(null, false));
  5. mockFn((err, val) => console.log(val)); // true
  6. mockFn((err, val) => console.log(val)); // false
  1. import {jest} from '@jest/globals';
  2. const mockFn = jest
  3. .fn<(cb: (a: null, b: boolean) => void) => void>()
  4. .mockImplementationOnce(cb => cb(null, true))
  5. .mockImplementationOnce(cb => cb(null, false));
  6. mockFn((err, val) => console.log(val)); // true
  7. mockFn((err, val) => console.log(val)); // false

When the mocked function runs out of implementations defined with .mockImplementationOnce(), it will execute the default implementation set with jest.fn(() => defaultValue) or .mockImplementation(() => defaultValue) if they were called:

  1. const mockFn = jest
  2. .fn(() => 'default')
  3. .mockImplementationOnce(() => 'first call')
  4. .mockImplementationOnce(() => 'second call');
  5. mockFn(); // 'first call'
  6. mockFn(); // 'second call'
  7. mockFn(); // 'default'
  8. mockFn(); // 'default'

mockFn.mockName(name)

用一个字符串来代替 'jest.fn()' 在测试结果的输出,用于表示正在引用哪个mock函数。

例如:

  1. const mockFn = jest.fn().mockName('mockedFunction');
  2. // mockFn();
  3. expect(mockFn).toHaveBeenCalled();

Will result in this error:

  1. expect(mockedFunction).toHaveBeenCalled()
  2. Expected number of calls: >= 1
  3. Received number of calls: 0

mockFn.mockReturnThis()

Shorthand for:

  1. jest.fn(function () {
  2. return this;
  3. });

mockFn.mockReturnValue(value)

Shorthand for:

  1. jest.fn().mockImplementation(() => value);

Accepts a value that will be returned whenever the mock function is called.

  • JavaScript
  • TypeScript
  1. const mock = jest.fn();
  2. mock.mockReturnValue(42);
  3. mock(); // 42
  4. mock.mockReturnValue(43);
  5. mock(); // 43
  1. import {jest} from '@jest/globals';
  2. const mock = jest.fn<() => number>();
  3. mock.mockReturnValue(42);
  4. mock(); // 42
  5. mock.mockReturnValue(43);
  6. mock(); // 43

mockFn.mockReturnValueOnce(value)

Shorthand for:

  1. jest.fn().mockImplementationOnce(() => value);

Accepts a value that will be returned for one call to the mock function. Accepts a value that will be returned for one call to the mock function. 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. When there are no more mockReturnValueOnce values to use, calls will return a value specified by mockReturnValue.

  • JavaScript
  • TypeScript
  1. const mockFn = jest
  2. .fn()
  3. .mockReturnValue('default')
  4. .mockReturnValueOnce('first call')
  5. .mockReturnValueOnce('second call');
  6. mockFn(); // 'first call'
  7. mockFn(); // 'second call'
  8. mockFn(); // 'default'
  9. mockFn(); // 'default'
  1. import {jest} from '@jest/globals';
  2. const mockFn = jest
  3. .fn<() => string>()
  4. .mockReturnValue('default')
  5. .mockReturnValueOnce('first call')
  6. .mockReturnValueOnce('second call');
  7. mockFn(); // 'first call'
  8. mockFn(); // 'second call'
  9. mockFn(); // 'default'
  10. mockFn(); // 'default'

mockFn.mockResolvedValue(value)

Shorthand for:

  1. jest.fn().mockImplementation(() => Promise.resolve(value));

Useful to mock async functions in async tests:

  • JavaScript
  • TypeScript
  1. test('async test', async () => {
  2. const asyncMock = jest.fn().mockResolvedValue(43);
  3. await asyncMock(); // 43
  4. });
  1. import {jest, test} from '@jest/globals';
  2. test('async test', async () => {
  3. const asyncMock = jest.fn<() => Promise<number>>().mockResolvedValue(43);
  4. await asyncMock(); // 43
  5. });

mockFn.mockResolvedValueOnce(value)

Shorthand for:

  1. jest.fn().mockImplementationOnce(() => Promise.resolve(value));

Useful to resolve different values over multiple async calls:

  • JavaScript
  • TypeScript
  1. test('async test', async () => {
  2. const asyncMock = jest
  3. .fn()
  4. .mockResolvedValue('default')
  5. .mockResolvedValueOnce('first call')
  6. .mockResolvedValueOnce('second call');
  7. await asyncMock(); // 'first call'
  8. await asyncMock(); // 'second call'
  9. await asyncMock(); // 'default'
  10. await asyncMock(); // 'default'
  11. });
  1. import {jest, test} from '@jest/globals';
  2. test('async test', async () => {
  3. const asyncMock = jest
  4. .fn<() => Promise<string>>()
  5. .mockResolvedValue('default')
  6. .mockResolvedValueOnce('first call')
  7. .mockResolvedValueOnce('second call');
  8. await asyncMock(); // 'first call'
  9. await asyncMock(); // 'second call'
  10. await asyncMock(); // 'default'
  11. await asyncMock(); // 'default'
  12. });

mockFn.mockRejectedValue(value)

Shorthand for:

  1. jest.fn().mockImplementation(() => Promise.reject(value));

Useful to create async mock functions that will always reject:

  • JavaScript
  • TypeScript
  1. test('async test', async () => {
  2. const asyncMock = jest
  3. .fn()
  4. .mockRejectedValue(new Error('Async error message'));
  5. await asyncMock(); // throws 'Async error message'
  6. });
  1. import {jest, test} from '@jest/globals';
  2. test('async test', async () => {
  3. const asyncMock = jest
  4. .fn<() => Promise<never>>()
  5. .mockRejectedValue(new Error('Async error message'));
  6. await asyncMock(); // throws 'Async error message'
  7. });

mockFn.mockRejectedValueOnce(value)

Shorthand for:

  1. jest.fn().mockImplementationOnce(() => Promise.reject(value));

Useful together with .mockResolvedValueOnce() or to reject with different exceptions over multiple async calls:

  • JavaScript
  • TypeScript
  1. test('async test', async () => {
  2. const asyncMock = jest
  3. .fn()
  4. .mockResolvedValueOnce('first call')
  5. .mockRejectedValueOnce(new Error('Async error message'));
  6. await asyncMock(); // 'first call'
  7. await asyncMock(); // throws 'Async error message'
  8. });
  1. import {jest, test} from '@jest/globals';
  2. test('async test', async () => {
  3. const asyncMock = jest
  4. .fn<() => Promise<string>>()
  5. .mockResolvedValueOnce('first call')
  6. .mockRejectedValueOnce(new Error('Async error message'));
  7. await asyncMock(); // 'first call'
  8. await asyncMock(); // throws 'Async error message'
  9. });

mockFn.withImplementation(fn, callback)

Accepts a function which should be temporarily used as the implementation of the mock while the callback is being executed.

  1. test('test', () => {
  2. const mock = jest.fn(() => 'outside callback');
  3. mock.withImplementation(
  4. () => 'inside callback',
  5. () => {
  6. mock(); // 'inside callback'
  7. },
  8. );
  9. mock(); // 'outside callback'
  10. });

mockFn.withImplementation can be used regardless of whether or not the callback is asynchronous (returns a thenable). If the callback is asynchronous a promise will be returned. Awaiting the promise will await the callback and reset the implementation.

  1. test('async test', async () => {
  2. const mock = jest.fn(() => 'outside callback');
  3. // We await this call since the callback is async
  4. await mock.withImplementation(
  5. () => 'inside callback',
  6. async () => {
  7. mock(); // 'inside callback'
  8. },
  9. );
  10. mock(); // 'outside callback'
  11. });

Replaced Properties

replacedProperty.replaceValue(value)

Changes the value of already replaced property. This is useful when you want to replace property and then adjust the value in specific tests. As an alternative, you can call jest.replaceProperty() multiple times on same property.

replacedProperty.restore()

Restores object’s property to the original value.

Beware that replacedProperty.restore() only works when the property value was replaced with jest.replaceProperty().

The restoreMocks configuration option is available to restore replaced properties automatically before each test.

TypeScript Usage

模拟函数 - 图5信息

The TypeScript examples from this page will only work as documented if you explicitly import Jest APIs:

  1. import {expect, jest, test} from '@jest/globals';

Consult the Getting Started guide for details on how to setup Jest with TypeScript.

jest.fn(implementation?)

Correct mock typings will be inferred if implementation is passed to jest.fn(). There are many use cases where the implementation is omitted. To ensure type safety you may pass a generic type argument (also see the examples above for more reference):

  1. import {expect, jest, test} from '@jest/globals';
  2. import type add from './add';
  3. import calculate from './calc';
  4. test('calculate calls add', () => {
  5. // Create a new mock that can be used in place of `add`.
  6. const mockAdd = jest.fn<typeof add>();
  7. // `.mockImplementation()` now can infer that `a` and `b` are `number`
  8. // and that the returned value is a `number`.
  9. mockAdd.mockImplementation((a, b) => {
  10. // Yes, this mock is still adding two numbers but imagine this
  11. // was a complex function we are mocking.
  12. return a + b;
  13. });
  14. // `mockAdd` is properly typed and therefore accepted by anything
  15. // requiring `add`.
  16. calculate(mockAdd, 1, 2);
  17. expect(mockAdd).toHaveBeenCalledTimes(1);
  18. expect(mockAdd).toHaveBeenCalledWith(1, 2);
  19. });

jest.Mock<T>

Constructs the type of a mock function, e.g. the return type of jest.fn(). It can be useful if you have to defined a recursive mock function:

  1. import {jest} from '@jest/globals';
  2. const sumRecursively: jest.Mock<(value: number) => number> = jest.fn(value => {
  3. if (value === 0) {
  4. return 0;
  5. } else {
  6. return value + fn(value - 1);
  7. }
  8. });

jest.Mocked<Source>

The jest.Mocked<Source> utility type returns the Source type wrapped with type definitions of Jest mock function.

  1. import {expect, jest, test} from '@jest/globals';
  2. import type {fetch} from 'node-fetch';
  3. jest.mock('node-fetch');
  4. let mockedFetch: jest.Mocked<typeof fetch>;
  5. afterEach(() => {
  6. mockedFetch.mockClear();
  7. });
  8. test('makes correct call', () => {
  9. mockedFetch = getMockedFetch();
  10. // ...
  11. });
  12. test('returns correct data', () => {
  13. mockedFetch = getMockedFetch();
  14. // ...
  15. });

Types of classes, functions or objects can be passed as type argument to jest.Mocked<Source>. If you prefer to constrain the input type, use: jest.MockedClass<Source>, jest.MockedFunction<Source> or jest.MockedObject<Source>.

jest.Replaced<Source>

The jest.Replaced<Source> utility type returns the Source type wrapped with type definitions of Jest replaced property.

src/utils.ts

  1. export function isLocalhost(): boolean {
  2. return process.env['HOSTNAME'] === 'localhost';
  3. }

src/__tests__/utils.test.ts

  1. import {afterEach, expect, it, jest} from '@jest/globals';
  2. import {isLocalhost} from '../utils';
  3. let replacedEnv: jest.Replaced<typeof process.env> | undefined = undefined;
  4. afterEach(() => {
  5. replacedEnv?.restore();
  6. });
  7. it('isLocalhost should detect localhost environment', () => {
  8. replacedEnv = jest.replaceProperty(process, 'env', {HOSTNAME: 'localhost'});
  9. expect(isLocalhost()).toBe(true);
  10. });
  11. it('isLocalhost should detect non-localhost environment', () => {
  12. replacedEnv = jest.replaceProperty(process, 'env', {HOSTNAME: 'example.com'});
  13. expect(isLocalhost()).toBe(false);
  14. });

jest.mocked(source, options?)

The mocked() helper method wraps types of the source object and its deep nested members with type definitions of Jest mock function. You can pass {shallow: true} as the options argument to disable the deeply mocked behavior.

Returns the source object.

song.ts

  1. export const song = {
  2. one: {
  3. more: {
  4. time: (t: number) => {
  5. return t;
  6. },
  7. },
  8. },
  9. };

song.test.ts

  1. import {expect, jest, test} from '@jest/globals';
  2. import {song} from './song';
  3. jest.mock('./song');
  4. jest.spyOn(console, 'log');
  5. const mockedSong = jest.mocked(song);
  6. // or through `jest.Mocked<Source>`
  7. // const mockedSong = song as jest.Mocked<typeof song>;
  8. test('deep method is typed correctly', () => {
  9. mockedSong.one.more.time.mockReturnValue(12);
  10. expect(mockedSong.one.more.time(10)).toBe(12);
  11. expect(mockedSong.one.more.time.mock.calls).toHaveLength(1);
  12. });
  13. test('direct usage', () => {
  14. jest.mocked(console.log).mockImplementation(() => {
  15. return;
  16. });
  17. console.log('one more time');
  18. expect(jest.mocked(console.log).mock.calls).toHaveLength(1);
  19. });

jest.Spied<Source>

Constructs the type of a spied class or function (i.e. the return type of jest.spyOn()).

__utils__/setDateNow.ts

  1. import {jest} from '@jest/globals';
  2. export function setDateNow(now: number): jest.Spied<typeof Date.now> {
  3. return jest.spyOn(Date, 'now').mockReturnValue(now);
  4. }
  1. import {afterEach, expect, type jest, test} from '@jest/globals';
  2. import {setDateNow} from './__utils__/setDateNow';
  3. let spiedDateNow: jest.Spied<typeof Date.now> | undefined = undefined;
  4. afterEach(() => {
  5. spiedDateNow?.mockReset();
  6. });
  7. test('renders correctly with a given date', () => {
  8. spiedDateNow = setDateNow(1_482_363_367_071);
  9. // ...
  10. expect(spiedDateNow).toHaveBeenCalledTimes(1);
  11. });

Types of a class or function can be passed as type argument to jest.Spied<Source>. If you prefer to constrain the input type, use: jest.SpiedClass<Source> or jest.SpiedFunction<Source>.

Use jest.SpiedGetter<Source> or jest.SpiedSetter<Source> to create the type of a spied getter or setter respectively.