Jest Mocking – Virtual Module

Ss black white code148972376

A powerful testing framework like Jest, is designed for efficiently testing JavaScript applications. You can use the jest.mock, one of the most useful API’s, to replace entire modules with mock implementations.

Sometimes you might have a need to mock a module that isn’t installed on your filesystem. The jest.mock(moduleName, factory, options), provides a third argument that allows you to mock a module that is not available, for example, one that might only be available at run time. Setting {virtual: true} within the third argument instructs Jest to mock the module even if it’s not physically available.

For example, let’s call the module runTimeOnly and the method we need to mock executeStep.

jest.mock(‘runTimeOnly’, () => {
  return {
    executeStep: jest.fn().mockImplmentation({
      return Promise.resolve(‘test123’);
    }),
  };
}, { virtual: true });

 

When providing the third argument {virtual: true}, the mock will be successful. Happy Testing!

 

Comments are disabled