3

I am trying to mock external dependency which is not yet published in npm repository.

import Utils from 'external-dependency';
jest.mock('external-dependency', () => ({
default: ()=> jest.fn()
}));

Above jest mocking display following error since that dependency not yet exist.

Cannot find module 'external-dependency'

How to mock non-exist dependency in Jest?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Prakash Gupta
  • 203
  • 1
  • 4
  • 13

1 Answers1

5

As stated in the reference,

The third argument can be used to create virtual mocks – mocks of modules that don't exist anywhere in the system

Also notice that jest.mock return value translates to CommonJS module by default. In case of ES module, it should be:

jest.mock('external-dependency', () => ({
  __esModule: true,
  default: ()=> jest.fn()
}), {virtual: true});
Estus Flask
  • 206,104
  • 70
  • 425
  • 565