12

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
  • 22,209
  • 7
  • 57
  • 64
Adrian Carolli
  • 695
  • 6
  • 21

2 Answers2

2

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

Pablo LION
  • 1,294
  • 6
  • 20
0

You need to mock an es6 module, which looks something like:

jest.mock('./path/to/the/file', () => ({
    _es6module: true,
    default: {
        publicMethodMock: jest.fn(), // ... the rest of you methods
    }
    })
);
magom001
  • 608
  • 6
  • 16