Skip to content

Instantly share code, notes, and snippets.

@robertolos
Last active December 19, 2022 23:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertolos/1025aa30b6813abdc229c9eb646c2e40 to your computer and use it in GitHub Desktop.
Save robertolos/1025aa30b6813abdc229c9eb646c2e40 to your computer and use it in GitHub Desktop.
Module mocking in ESM
// # https://jestjs.io/docs/ecmascript-modules#module-mocking-in-esm
// #### module.ts ####
import { getData } from "./submodule";
export const myModule = () => {
return getData();
};
// #### submodule.ts ####
export const getData = () => {
return "real implementation";
};
// #### module.spec.ts ####
import { jest } from "@jest/globals";
jest.unstable_mockModule("./submodule", () => ({
getData: jest.fn().mockImplementation(() => "mocked"),
}));
const { myModule } = await import("./module");
describe("esm module", () => {
it("should return the mocked value for the getData function in submodule.ts", () => {
expect(myModule()).toBe("mocked");
});
});
// #### jest.config.ts ####
import type {JestConfigWithTsJest} from 'ts-jest'
const jestConfig: JestConfigWithTsJest = {
extensionsToTreatAsEsm: [".ts"],
moduleNameMapper: {
"^(\\.{1,2}/.*)\\.js$": "$1",
},
transform: {
"^.+\\.(ts|tsx)$": [
"ts-jest",
{
useESM: true,
},
],
},
testMatch: ["**/*.spec.ts"],
};
export default jestConfig;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment