Jest - Mock


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.


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

Mock return values

Jest mock function can return mock value


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


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();

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));

Discover More
Javascript - Jest Test Runner

Jest is a test runner from Facebook for client-side JavaScript applications and React applications specifically. Jest ships with jsdom for DOM manipulation testing....

Share this page:
Follow us:
Task Runner