Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move common mocking code to a separate file containing a Jest manual mock

Tags:

There is a mock I use in many places, so I want to move it into a separate file that can be reused.

I think Jest calls this a "manual mock". However I don't want to use the __mocks__ convention.

The top of the file being tested:

import * as dotenvSafe from "dotenv-safe";

The manual mock file:

const dotenvSafe: any = jest.genMockFromModule("dotenv-safe");

dotenvSafe.load = jest.fn(() => {     // the function I want to mock
  return {
    error: undefined,
    parsed: [],
  };
});

export default dotenvSafe;

At the top of the test file, I tried various things:

  1. jest.setMock("dotenv-safe", "../../mocks/dotenv-safe");
    Doesn't work. The code being tested gets "../../mocks/dotenv-safe.mock" instead of a module.

  2. jest.mock("dotenv-safe", () => require("../../mocks/dotenv-safe"));
    Doesn't work - The code being tested throws TypeError: dotenvSafe.load is not a function.

  3. jest.mock("dotenv-safe", () => { return { load: jest.fn(() => ({error: undefined, parsed: []})) }; });
    Does work! But the mock is inline, and I want to move it to a separate file. I don't want to repeat this in every file.

What is the correct syntax?

like image 643
lonix Avatar asked Feb 01 '19 08:02

lonix


People also ask

How do I call a Jest function from another file?

Solution #1 using jest. beforeEach(() => { jest. spyOn(utils, "getData"). mockReturnValue("mocked message"); });

How do I mock an entire file in Jest?

To mock any file first step is to tell Jest that you are planning to mock it. After telling Jest that you will be mocking the particular file, you need to tell Jest what it should do, instead of executing the function. You can increase a counter or return a particular value to know that the function was called.

What is Jest fn ()?

The Jest library provides the jest. fn() function for creating a “mock” function. An optional implementation function may be passed to jest. fn() to define the mock function's behavior and return value. The mock function's behavior may be further specified using various methods provided to the mock function such as .

Where do you put Jest mocks?

Mocking Node modules​ If the module you are mocking is a Node module (e.g.: lodash ), the mock should be placed in the __mocks__ directory adjacent to node_modules (unless you configured roots to point to a folder other than the project root) and will be automatically mocked. There's no need to explicitly call jest.


1 Answers

require("../../mocks/dotenv-safe") equals to module exports. It's default export that is used, so it should be:

jest.mock("dotenv-safe", () => require("../../mocks/dotenv-safe").default);
like image 61
Estus Flask Avatar answered Nov 15 '22 11:11

Estus Flask