Table of Contents

Jest - Mock

About

Test - Mock in Jest

Mocking is just replacing a function by another called a mocking function.

In Jest mocking function can replace the code executed but they also record all call made to them creating a command history.

Features

Function Call history

Mock function can register their call against their .mock property where assertion can be made.

Example from the Doc

function forEach(items, callback) {
    for (let index = 0; index < items.length; index++) {
        callback(items[index]);
    }
}
const mockCallback = jest.fn(x => 42 + x);
forEach([0, 1], mockCallback);
test('Injection Test', () => {

    // The mock function was called twice
    expect(mockCallback.mock.calls.length).toBe(2);

    // The first argument of the first call to the function was 0
    expect(mockCallback.mock.calls[0][0]).toBe(0);

    // The first argument of the second call to the function was 1
    expect(mockCallback.mock.calls[1][0]).toBe(1);

    // The return value of the first call to the function was 42
    expect(mockCallback.mock.results[0].value).toBe(42);
}
)

Mock return values

Jest mock function can return mock value

Sync

From Doc

const myMock = jest.fn();
console.log(myMock());
// > undefined
myMock
  .mockReturnValueOnce(10) 
  .mockReturnValueOnce('x')
  .mockReturnValue(true);
console.log(myMock(), myMock(), myMock(), myMock());
// > 10, 'x', true, true

Async

How to mock a function that return a promise.

const users = [{name: 'Bob'}];
const resp = {data: users};
const myMock = jest.fn();
myMock.mockResolvedValue(resp);

Mock module / function

Mocking module happens via variable or path injection

Example from the doc

// After the import, you can define that a variable will be mocked
import lib from '../lib';
jest.mock('lib');
//
// Or before the import
jest.mock('../lib'); 
const lib = require('../lib');
// Adding return value to a subfunction
lib.subfunction
  .mockReturnValueOnce(true)
  .mockReturnValueOnce(false);
// Mocking the function
lib.subfunction.mockImplementation(() => 42);
// Mocking the function differently for each call
lib.subfunction
  .mockImplementationOnce(cb => cb(null, true))
  .mockImplementationOnce(cb => cb(null, false));