Categories
JavaScript Answers

How to mock inner function with Jest and JavaScript?

Spread the love

Sometimes, we want to mock inner function with Jest and JavaScript.

In this article, we’ll look at how to mock inner function with Jest and JavaScript.

How to mock inner function with Jest and JavaScript?

To mock inner function with Jest and JavaScript, we should export the inner function in a module.

For instance, we write

funcB.js

export const funcB = () => {
  return "original";
};

Then we import it with

foo.js

import { funcB } from "./funcB";

export const funcA = () => {
  return funcB();
};

Next, we write tests for funcA and funcB with

import * as funcBModule from "./funcB";
import { funcA } from "./foo";

describe("helper", () => {
  test("test funcB", () => {
    expect(funcBModule.funcB()).toBe("original");
  });

  test("test funcA", () => {
    const spy = jest.spyOn(funcBModule, "funcB");
    spy.mockReturnValue("mocked");

    expect(funcA()).toBe("mocked");

    spy.mockRestore();
  });
});

We funcBModule.funcB in the first test.

And we create a spy and mock the return value of funcB in the 2nd test with

const spy = jest.spyOn(funcBModule, "funcB");
spy.mockReturnValue("mocked");

And we call funcA after that.

Finally we call mockRestore to restore the mocks to their original values.

Conclusion

To mock inner function with Jest and JavaScript, we should export the inner function in a module.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *