Last active
December 19, 2022 23:15
-
-
Save robertolos/1025aa30b6813abdc229c9eb646c2e40 to your computer and use it in GitHub Desktop.
Module mocking in ESM
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// # 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