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:
jest.setMock("dotenv-safe", "../../mocks/dotenv-safe");
Doesn't work. The code being tested gets "../../mocks/dotenv-safe.mock"
instead of a module.
jest.mock("dotenv-safe", () => require("../../mocks/dotenv-safe"));
Doesn't work - The code being tested throws TypeError: dotenvSafe.load is not a function
.
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?
Solution #1 using jest. beforeEach(() => { jest. spyOn(utils, "getData"). mockReturnValue("mocked message"); });
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.
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 .
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With