Version: 27.2

模拟函数

Mcok 函数也被叫做 “间谍”, 因为他们可以让你监视代码间接调用函数的行为,而不是仅测试函数输出结果。 你可以通过 jest.fn() 创建 mock 函数。 当调用没有执行,mock 函数会返回undefined

方法


Reference

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

Resets all information stored in the mockFn.mock.calls, mockFn.mock.instances and mockFn.mock.results arrays. Often this is useful when you want to clean up a mocks usage data between two assertions.

Beware that mockClear will replace mockFn.mock, not just these three properties! 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). (注意重置一个 spy 将导致一个没有返回值的函数)。

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(). Thus you have to take care of restoration yourself when manually assigning jest.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.

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:

SomeClass.js

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

OtherModule.test.js

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

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

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

  1. // Assume `add` is imported and used within `calculate`.
  2. // Assume `add` is imported and used within `calculate`.
  3. import add from './add';
  4. import calculate from './calc';
  5. jest.mock('./add');
  6. // Our mock of `add` is now fully typed
  7. const mockAdd = add as jest.MockedFunction<typeof add>;
  8. test('calculate calls add', () => {
  9. calculate('Add', 1, 2);
  10. expect(mockAdd).toBeCalledTimes(1);
  11. expect(mockAdd).toBeCalledWith(1, 2);
  12. });

Example using jest.fn:

  1. // Here `add` is imported for its type
  2. import 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. // Here `add` is imported for its type
  7. import add from './add';
  8. import calculate from './calc';
  9. test('calculate calls add', () => {
  10. // Create a new mock that can be used in place of `add`.
  11. const mockAdd = jest.fn() as jest.MockedFunction<typeof add>;
  12. // Note: You can use the `jest.fn` type directly like this if you want:
  13. // const mockAdd = jest.fn<ReturnType<typeof add>, Parameters<typeof add>>();
  14. // `jest.MockedFunction` is a more friendly shortcut.
  15. // Now we can easily set up mock implementations.
  16. // All the `.mock*` API can now give you proper types for `add`.
  17. // https://jestjs.io/docs/en/mock-function-api
  18. // `.mockImplementation` can now infer that `a` and `b` are `number`
  19. // and that the returned value is a `number`.
  20. mockAdd.mockImplementation((a, b) => {
  21. // Yes, this mock is still adding two numbers but imagine this
  22. // was a complex function we are mocking.
  23. return a + b
  24. }));
  25. // `mockAdd` is properly typed and therefore accepted by
  26. // anything requiring `add`.
  27. calculate(mockAdd, 1 , 2);
  28. expect(mockAdd).toBeCalledTimes(1);
  29. expect(mockAdd).toBeCalledWith(1, 2);
  30. })
  31. // Now we can easily set up mock implementations.
  32. // All the `.mock*` API can now give you proper types for `add`.
  33. // https://jestjs.io/docs/mock-function-api
  34. // `.mockImplementation` can now infer that `a` and `b` are `number`
  35. // and that the returned value is a `number`.
  36. mockAdd.mockImplementation((a, b) => {
  37. // Yes, this mock is still adding two numbers but imagine this
  38. // was a complex function we are mocking.
  39. return a + b;
  40. });
  41. // `mockAdd` is properly typed and therefore accepted by
  42. // anything requiring `add`.
  43. calculate(mockAdd, 1, 2);
  44. expect(mockAdd).toBeCalledTimes(1);
  45. expect(mockAdd).toBeCalledWith(1, 2);
  46. });

jest.MockedClass

jest.MockedClass is available in the @types/jest module from version 24.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:

  1. import SoundPlayer from '../sound-player';
  2. import SoundPlayerConsumer from '../sound-player-consumer';
  3. jest.mock('../sound-player'); // SoundPlayer is now a mock constructor
  4. const SoundPlayerMock = SoundPlayer as jest.MockedClass<typeof SoundPlayer>;
  5. beforeEach(() => {
  6. // Clear all instances and calls to constructor and all methods:
  7. SoundPlayerMock.mockClear();
  8. });
  9. it('We can check if the consumer called the class constructor', () => {
  10. const soundPlayerConsumer = new SoundPlayerConsumer();
  11. expect(SoundPlayerMock).toHaveBeenCalledTimes(1);
  12. });
  13. it('We can check if the consumer called a method on the class instance', () => {
  14. // Show that mockClear() is working:
  15. expect(SoundPlayerMock).not.toHaveBeenCalled();
  16. const soundPlayerConsumer = new SoundPlayerConsumer();
  17. // Constructor should have been called again:
  18. expect(SoundPlayerMock).toHaveBeenCalledTimes(1);
  19. const coolSoundFileName = 'song.mp3';
  20. soundPlayerConsumer.playSomethingCool();
  21. // mock.instances is available with automatic mocks:
  22. const mockSoundPlayerInstance = SoundPlayerMock.mock.instances[0];
  23. // However, it will not allow access to `.mock` in TypeScript as it
  24. // is returning `SoundPlayer`. Instead, you can check the calls to a
  25. // method like this fully typed:
  26. expect(SoundPlayerMock.prototype.playSoundFile.mock.calls[0][0]).toEqual(
  27. coolSoundFileName,
  28. );
  29. // Equivalent to above check:
  30. expect(SoundPlayerMock.prototype.playSoundFile).toHaveBeenCalledWith(
  31. coolSoundFileName,
  32. );
  33. expect(SoundPlayerMock.prototype.playSoundFile).toHaveBeenCalledTimes(1);
  34. }); Instead, you can check the calls to a
  35. // method like this fully typed:
  36. expect(SoundPlayerMock.prototype.playSoundFile.mock.calls[0][0]).toEqual(
  37. coolSoundFileName,
  38. );
  39. // Equivalent to above check:
  40. expect(SoundPlayerMock.prototype.playSoundFile).toHaveBeenCalledWith(
  41. coolSoundFileName,
  42. );
  43. expect(SoundPlayerMock.prototype.playSoundFile).toHaveBeenCalledTimes(1);
  44. });