Mock functions make it easy to test the links between code by erasing the actual implementation of a function, capturing calls to the function (and the parameters passed in those calls), capturing instances of constructor functions when instantiated with new, and allowing test-time configuration of return values.

There are two ways to mock functions: Either by creating a mock function to use in test code, or writing a manual mock to override a module dependency.

Using a mock function

Let's imagine we're testing an implementation of a function forEach, which invokes a callback for each item in a supplied array.

  1. function forEach(items, callback) {
  2. for (let index = 0; index < items.length; index++) {
  3. callback(items[index]);
  4. }
  5. }

To test this function, we can use a mock function, and inspect the mock's state to ensure the callback is invoked as expected.

  1. const mockCallback = jest.fn(x => 42 + x);
  2. forEach([0, 1], mockCallback);
  3. // The mock function is called twice
  4. expect(mockCallback.mock.calls.length).toBe(2);
  5. // The first argument of the first call to the function was 0
  6. expect(mockCallback.mock.calls[0][0]).toBe(0);
  7. // The first argument of the second call to the function was 1
  8. expect(mockCallback.mock.calls[1][0]).toBe(1);
  9. // The return value of the first call to the function was 42
  10. expect(mockCallback.mock.results[0].value).toBe(42);

.mock property

All mock functions have this special .mock property, which is where data about how the function has been called and what the function returned is kept. The .mock property also tracks the value of this for each call, so it is possible to inspect this as well:

  1. const myMock = jest.fn();
  2. const a = new myMock();
  3. const b = {};
  4. const bound = myMock.bind(b);
  5. bound();
  6. console.log(myMock.mock.instances);
  7. // > [ <a>, <b> ]

These mock members are very useful in tests to assert how these functions get called, instantiated, or what they returned:

  1. // The function was called exactly once
  2. expect(someMockFunction.mock.calls.length).toBe(1);
  3. // The first arg of the first call to the function was 'first arg'
  4. expect(someMockFunction.mock.calls[0][0]).toBe('first arg');
  5. // The second arg of the first call to the function was 'second arg'
  6. expect(someMockFunction.mock.calls[0][1]).toBe('second arg');
  7. // The return value of the first call to the function was 'return value'
  8. expect(someMockFunction.mock.results[0].value).toBe('return value');
  9. // This function was instantiated exactly twice
  10. expect(someMockFunction.mock.instances.length).toBe(2);
  11. // The object returned by the first instantiation of this function
  12. // had a `name` property whose value was set to 'test'
  13. expect(someMockFunction.mock.instances[0].name).toEqual('test');

Mock Return Values

Mock functions can also be used to inject test values into your code during a test:

  1. const myMock = jest.fn();
  2. console.log(myMock());
  3. // > undefined
  4. myMock
  5. .mockReturnValueOnce(10)
  6. .mockReturnValueOnce('x')
  7. .mockReturnValue(true);
  8. console.log(myMock(), myMock(), myMock(), myMock());
  9. // > 10, 'x', true, true

Mock functions are also very effective in code that uses a functional continuation-passing style. Code written in this style helps avoid the need for complicated stubs that recreate the behavior of the real component they're standing in for, in favor of injecting values directly into the test right before they're used.

  1. const filterTestFn = jest.fn();
  2. // Make the mock return `true` for the first call,
  3. // and `false` for the second call
  4. filterTestFn.mockReturnValueOnce(true).mockReturnValueOnce(false);
  5. const result = [11, 12].filter(filterTestFn);
  6. console.log(result);
  7. // > [11]
  8. console.log(filterTestFn.mock.calls);
  9. // > [ [11], [12] ]

Most real-world examples actually involve getting ahold of a mock function on a dependent component and configuring that, but the technique is the same. In these cases, try to avoid the temptation to implement logic inside of any function that's not directly being tested.

Mocking Modules

Suppose we have a class that fetches users from our API. The class uses axios to call the API then returns the data attribute which contains all the users:

  1. // users.js
  2. import axios from 'axios';
  3. class Users {
  4. static all() {
  5. return axios.get('/users.json').then(resp => resp.data);
  6. }
  7. }
  8. export default Users;

Now, in order to test this method without actually hitting the API (and thus creating slow and fragile tests), we can use the jest.mock(…) function to automatically mock the axios module.

Once we mock the module we can provide a mockResolvedValue for .get that returns the data we want our test to assert against. In effect, we are saying that we want axios.get('/users.json') to return a fake response.

  1. // users.test.js
  2. import axios from 'axios';
  3. import Users from './users';
  4. jest.mock('axios');
  5. test('should fetch users', () => {
  6. const users = [{name: 'Bob'}];
  7. const resp = {data: users};
  8. axios.get.mockResolvedValue(resp);
  9. // or you could use the following depending on your use case:
  10. // axios.get.mockImplementation(() => Promise.resolve(resp))
  11. return Users.all().then(resp => expect(resp.data).toEqual(users));
  12. });

Mock Implementations

Still, there are cases where it's useful to go beyond the ability to specify return values and full-on replace the implementation of a mock function. This can be done with jest.fn or the mockImplementationOnce method on mock functions.

  1. const myMockFn = jest.fn(cb => cb(null, true));
  2. myMockFn((err, val) => console.log(val));
  3. // > true

The mockImplementation method is useful when you need to define the default implementation of a mock function that is created from another module:

  1. // foo.js
  2. module.exports = function() {
  3. // some implementation;
  4. };
  5. // test.js
  6. jest.mock('../foo'); // this happens automatically with automocking
  7. const foo = require('../foo');
  8. // foo is a mock function
  9. foo.mockImplementation(() => 42);
  10. foo();
  11. // > 42

When you need to recreate a complex behavior of a mock function such that multiple function calls produce different results, use the mockImplementationOnce method:

  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));
  6. // > true
  7. myMockFn((err, val) => console.log(val));
  8. // > false

When the mocked function runs out of implementations defined with mockImplementationOnce, it will execute the default implementation set with jest.fn (if it is defined):

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

For cases where we have methods that are typically chained (and thus always need to return this), we have a sugary API to simplify this in the form of a .mockReturnThis() function that also sits on all mocks:

  1. const myObj = {
  2. myMethod: jest.fn().mockReturnThis(),
  3. };
  4. // is the same as
  5. const otherObj = {
  6. myMethod: jest.fn(function() {
  7. return this;
  8. }),
  9. };

Mock Names

You can optionally provide a name for your mock functions, which will be displayed instead of "jest.fn()" in test error output. Use this if you want to be able to quickly identify the mock function reporting an error in your test output.

  1. const myMockFn = jest
  2. .fn()
  3. .mockReturnValue('default')
  4. .mockImplementation(scalar => 42 + scalar)
  5. .mockName('add42');

Custom Matchers

Finally, in order to make it simpler to assert how mock functions have been called, we've added some custom matcher functions for you:

  1. // The mock function was called at least once
  2. expect(mockFunc).toBeCalled();
  3. // The mock function was called at least once with the specified args
  4. expect(mockFunc).toBeCalledWith(arg1, arg2);
  5. // The last call to the mock function was called with the specified args
  6. expect(mockFunc).lastCalledWith(arg1, arg2);
  7. // All calls and the name of the mock is written as a snapshot
  8. expect(mockFunc).toMatchSnapshot();

These matchers are really just sugar for common forms of inspecting the .mock property. You can always do this manually yourself if that's more to your taste or if you need to do something more specific:

  1. // The mock function was called at least once
  2. expect(mockFunc.mock.calls.length).toBeGreaterThan(0);
  3. // The mock function was called at least once with the specified args
  4. expect(mockFunc.mock.calls).toContain([arg1, arg2]);
  5. // The last call to the mock function was called with the specified args
  6. expect(mockFunc.mock.calls[mockFunc.mock.calls.length - 1]).toEqual([
  7. arg1,
  8. arg2,
  9. ]);
  10. // The first arg of the last call to the mock function was `42`
  11. // (note that there is no sugar helper for this specific of an assertion)
  12. expect(mockFunc.mock.calls[mockFunc.mock.calls.length - 1][0]).toBe(42);
  13. // A snapshot will check that a mock was invoked the same number of times,
  14. // in the same order, with the same arguments. It will also assert on the name.
  15. expect(mockFunc.mock.calls).toEqual([[arg1, arg2]]);
  16. expect(mockFunc.getMockName()).toBe('a mock name');

For a complete list of matchers, check out the reference docs.

原文: https://jestjs.io/docs/en/mock-functions