Jest - Mock

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

3 - Features

3.1 - Function Call history

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

Example from the Doc

  • The function to test

function forEach(items, callback) {
    for (let index = 0; index < items.length; index++) {

  • The mock function definition

const mockCallback = jest.fn(x => 42 + x);

  • The injection

forEach([0, 1], mockCallback);

  • The Test based on .mock property that contains the history of the mock function call

test('Injection Test', () => {

    // The mock function was called twice

    // The first argument of the first call to the function was 0

    // The first argument of the second call to the function was 1

    // The return value of the first call to the function was 42

3.2 - Mock return values

Jest mock function can return mock value

3.2.1 - Sync

From Doc

  • Define a mock function

const myMock = jest.fn();
// > undefined

  • Add some value to a stack of values


  • Destack them

console.log(myMock(), myMock(), myMock(), myMock());
// > 10, 'x', true, true

3.2.2 - Async

How to mock a function that return a promise.

  • Data

const users = [{name: 'Bob'}];
const resp = {data: users};

  • Mock function definition

const myMock = jest.fn();

3.3 - Mock module / function

Mocking module happens via variable or path injection

Example from the doc

  • Mocking:

// After the import, you can define that a variable will be mocked
import lib from '../lib';
// Or before the import
const lib = require('../lib');

  • lib and all sub function will become a mocked function/library where all mock function can be called to set up a mock.

// Adding return value to a subfunction
// Mocking the function
lib.subfunction.mockImplementation(() => 42);
// Mocking the function differently for each call
  .mockImplementationOnce(cb => cb(null, true))
  .mockImplementationOnce(cb => cb(null, false));

Data Science
Data Analysis
Data Science
Linear Algebra Mathematics

Powered by ComboStrap