11

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.

skyboyer
  • 19,620
  • 7
  • 50
  • 62
Adrian Carolli
  • 645
  • 6
  • 21

1 Answers1

0

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

Pablion
  • 318
  • 2
  • 11