Mocking ES modules with Jest

code, jest β€’13th March 2019

TODO: Write things like this more often 🀐

Over the past few months I found myself googling how to mock modules in jest several times and every time it took more then I expected so I finally decided to write it down 🀯..

// myFavoriteBike.js
export const bike = "YT Jeffsy"
export default () => "My favorite bike is ${bike}"

And in your test file just mock it manually(this overwrites anything in __mocks__)

// myFavoriteBike.test.js
jest.mock("./myFavoriteBike", () => ({
  __esModule: true, // this is what makes ES modules work
  default: () => "My favorite bike is Canyon Endurace",
  bike: "Canyon Endurace",

import favoriteBike, { bike } from "./myFavoriteBike";
favoriteBike(); // "My favorite bike is Canyon Endurace"
bike // "Canyon Endurace"