Mock Functions

Mock functions allow you 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.

forEach.js

  1. export 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.

forEach.test.js

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

.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 myMock1 = jest.fn();
  2. const a = new myMock1();
  3. console.log(myMock1.mock.instances);
  4. // > [ <a> ]
  5. const myMock2 = jest.fn();
  6. const b = {};
  7. const bound = myMock2.bind(b);
  8. bound();
  9. console.log(myMock2.mock.contexts);
  10. // > [ <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).toHaveLength(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. // The function was called with a certain `this` context: the `element` object.
  10. expect(someMockFunction.mock.contexts[0]).toBe(element);
  11. // This function was instantiated exactly twice
  12. expect(someMockFunction.mock.instances.length).toBe(2);
  13. // The object returned by the first instantiation of this function
  14. // had a `name` property whose value was set to 'test'
  15. expect(someMockFunction.mock.instances[0].name).toBe('test');
  16. // The first argument of the last call to the function was 'test'
  17. expect(someMockFunction.mock.lastCall[0]).toBe('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.mockReturnValueOnce(10).mockReturnValueOnce('x').mockReturnValue(true);
  5. console.log(myMock(), myMock(), myMock(), myMock());
  6. // > 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(num => filterTestFn(num));
  6. console.log(result);
  7. // > [11]
  8. console.log(filterTestFn.mock.calls[0][0]); // 11
  9. console.log(filterTestFn.mock.calls[1][0]); // 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:

users.js

  1. import axios from 'axios';
  2. class Users {
  3. static all() {
  4. return axios.get('/users.json').then(resp => resp.data);
  5. }
  6. }
  7. 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.

users.test.js

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

Mocking Partials

Subsets of a module can be mocked and the rest of the module can keep their actual implementation:

foo-bar-baz.js

  1. export const foo = 'foo';
  2. export const bar = () => 'bar';
  3. export default () => 'baz';
  1. //test.js
  2. import defaultExport, {bar, foo} from '../foo-bar-baz';
  3. jest.mock('../foo-bar-baz', () => {
  4. const originalModule = jest.requireActual('../foo-bar-baz');
  5. //Mock the default export and named export 'foo'
  6. return {
  7. __esModule: true,
  8. ...originalModule,
  9. default: jest.fn(() => 'mocked baz'),
  10. foo: 'mocked foo',
  11. };
  12. });
  13. test('should do a partial mock', () => {
  14. const defaultExportResult = defaultExport();
  15. expect(defaultExportResult).toBe('mocked baz');
  16. expect(defaultExport).toHaveBeenCalled();
  17. expect(foo).toBe('mocked foo');
  18. expect(bar()).toBe('bar');
  19. });

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:

foo.js

  1. module.exports = function () {
  2. // some implementation;
  3. };

test.js

  1. jest.mock('../foo'); // this happens automatically with automocking
  2. const foo = require('../foo');
  3. // foo is a mock function
  4. foo.mockImplementation(() => 42);
  5. foo();
  6. // > 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 the test error output. Use .mockName() 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 less demanding 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).toHaveBeenCalled();
  3. // The mock function was called at least once with the specified args
  4. expect(mockFunc).toHaveBeenCalledWith(arg1, arg2);
  5. // The last call to the mock function was called with the specified args
  6. expect(mockFunc).toHaveBeenLastCalledWith(arg1, arg2);
  7. // All calls and the name of the mock is written as a snapshot
  8. expect(mockFunc).toMatchSnapshot();

These matchers are 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).toContainEqual([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.