How to do jest mocking for non-exist external dependency

2k views Asked by At

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?

1

There are 1 answers

0
Estus Flask On BEST ANSWER

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});