Skip to content

Instantly share code, notes, and snippets.

@spencerfeng
Created December 13, 2023 11:32
Show Gist options
  • Save spencerfeng/413d76e33f90d3a35822aa995e23bbb9 to your computer and use it in GitHub Desktop.
Save spencerfeng/413d76e33f90d3a35822aa995e23bbb9 to your computer and use it in GitHub Desktop.
For tutorial: Mastering the Art of Mocking ES Modules in Jest
import { jest } from "@jest/globals"
let mockedDependencyValue
jest.unstable_mockModule("./dependency.js", () => ({
dependency: () => mockedDependencyValue
}));
describe("functionToTest", () => {
afterEach(() => {
jest.restoreAllMocks()
})
it("should return the correct value 1", async () => {
mockedDependencyValue = "the mocked dependency 1"
const { functionToTest } = await import("./functionToTest.js")
expect(functionToTest()).toBe(mockedDependencyValue)
})
it("should return the correct value 2", async () => {
mockedDependencyValue = "the mocked dependency 2"
const { functionToTest } = await import("./functionToTest.js")
expect(functionToTest()).toBe(mockedDependencyValue)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment