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++) {
        callback(items[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
    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);
}
)

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();
console.log(myMock());
// > undefined

  • Add some value to a stack of values

myMock
  .mockReturnValueOnce(10) 
  .mockReturnValueOnce('x')
  .mockReturnValue(true);

  • 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();
myMock.mockResolvedValue(resp);

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';
jest.mock('lib');
//
// Or before the import
jest.mock('../lib'); 
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
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));


Data Science
Data Analysis
Statistics
Data Science
Linear Algebra Mathematics
Trigonometry

Powered by ComboStrap