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.

方法


参考

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:

  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. 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:

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

Resets all information stored in the mockFn.mock.calls and mockFn.mock.instances arrays.

Often this is useful when you want to clean up a mock's usage data between two assertions.

Beware that mockClear will replace mockFn.mock, not just mockFn.mock.calls and 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.

当您想要完全重置 mock 到初始状态时,这是有用。 (注意重置一个 spy 将导致一个没有返回值的函数)。

Beware that mockReset will replace mockFn.mock, not just mockFn.mock.calls and 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.

This is useful when you want to mock functions in certain test cases and restore the original implementation in others.

Beware that 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().

The restoreMocks configuration option is available to restore mocks automatically between tests.

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.

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

例如:

  1. const mockFn = jest.fn().mockImplementation(scalar => 42 + scalar);
  2. // or: jest.fn(scalar => 42 + scalar);
  3. const a = mockFn(0);
  4. const b = mockFn(1);
  5. a === 42; // true
  6. b === 43; // true
  7. mockFn.mock.calls[0][0] === 0; // true
  8. mockFn.mock.calls[1][0] === 1; // true

mockImplementation can also be used to mock class constructors:

  1. // SomeClass.js
  2. module.exports = class SomeClass {
  3. m(a, b) {}
  4. };
  5. // OtherModule.test.js
  6. jest.mock('./SomeClass'); // this happens automatically with automocking
  7. const SomeClass = require('./SomeClass');
  8. const mMock = jest.fn();
  9. SomeClass.mockImplementation(() => {
  10. return {
  11. m: mMock,
  12. };
  13. });
  14. const some = new SomeClass();
  15. some.m('a', 'b');
  16. 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.

  1. const myMockFn = jest
  2. .fn()
  3. .mockImplementationOnce(cb => cb(null, true))
  4. .mockImplementationOnce(cb => cb(null, false));
  5. myMockFn((err, val) => console.log(val)); // true
  6. myMockFn((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 myMockFn = jest
  2. .fn(() => 'default')
  3. .mockImplementationOnce(() => 'first call')
  4. .mockImplementationOnce(() => 'second call');
  5. // 'first call', 'second call', 'default', 'default'
  6. 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.

例如:

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

Will result in this error:

  1. expect(mockedFunction).toHaveBeenCalled()
  2. Expected mock function "mockedFunction" to have been called, but it was not called.

mockFn.mockReturnThis()

Syntactic sugar function for:

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

mockFn.mockReturnValue(value)

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

  1. const mock = jest.fn();
  2. mock.mockReturnValue(42);
  3. mock(); // 42
  4. mock.mockReturnValue(43);
  5. mock(); // 43

mockFn.mockReturnValueOnce(value)

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.

  1. const myMockFn = jest
  2. .fn()
  3. .mockReturnValue('default')
  4. .mockReturnValueOnce('first call')
  5. .mockReturnValueOnce('second call');
  6. // 'first call', 'second call', 'default', 'default'
  7. console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn());

mockFn.mockResolvedValue(value)

Syntactic sugar function for:

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

Useful to mock async functions in async tests:

  1. test('async test', async () => {
  2. const asyncMock = jest.fn().mockResolvedValue(43);
  3. await asyncMock(); // 43
  4. });

mockFn.mockResolvedValueOnce(value)

Syntactic sugar function for:

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

Useful to resolve different values over multiple async calls:

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

mockFn.mockRejectedValue(value)

Syntactic sugar function for:

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

Useful to create async mock functions that will always reject:

  1. test('async test', async () => {
  2. const asyncMock = jest.fn().mockRejectedValue(new Error('Async error'));
  3. await asyncMock(); // throws "Async error"
  4. });

mockFn.mockRejectedValueOnce(value)

Syntactic sugar function for:

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

Example usage:

  1. test('async test', async () => {
  2. const asyncMock = jest
  3. .fn()
  4. .mockResolvedValueOnce('first call')
  5. .mockRejectedValueOnce(new Error('Async error'));
  6. await asyncMock(); // first call
  7. await asyncMock(); // throws "Async error"
  8. });