Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest Mock a destructured import/require

How can mock a destructured import in the form of

const {mymodule} = require('@org/package')

I have a custom library in a private repository that exports a function from the index.js file like this

// index.js
exports.mymodule = require('./mymodule')

Using jest I tried to mock the module like this

jest.mock('@org/package', () => ({
   func: jest.fn()
}))

However, when I check the value of {module} it remains null. Then, when remove the curly brackets from module, it becomes populated with the mock module.

How can I mock the destructured module?

like image 277
navig8tr Avatar asked Oct 11 '25 22:10

navig8tr


1 Answers

Module object is supposed to have mymodule property, while mocked module doesn't have it. To ensure the interoperation with ES modules, CommonJS export should have __esModule as well:

jest.mock('@org/package', () => ({
  __esModule: true,
  mymodule: {
    func: jest.fn()
  }
}))
like image 91
Estus Flask Avatar answered Oct 14 '25 12:10

Estus Flask