'How to mock a ES6 singleton class with Jest?

I have a dependency that is a singleton class like so:

// dependency.js
class Dependency {
   foo() { ... }
}
export default new Dependency();

I'm trying to mock this class with Jest but since its a singleton I'm not sure how to mock it. I tried this:

jest.mock('../Dependency', () => {
  return { foo: jest.fn() };
});

But that didn't work.



Solution 1:[1]

The jest.mock accepts a module name instead of a class name. The string should be the same as when you use require. Assuming your dependency.js is in the parent folder, it should be like this:

jest.mock('../dependency', () => {
  return { foo: jest.fn() };
});

However, this requires the '../dependency' module to export a foo, like this: (see More details on mock)

// dependency.js
// class Dependency {
   foo() { ... }
// }
export {foo};

Mocking a class is more complicated, you can see the implementation here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pablion