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 throwsTypeError: 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?