Jest TypeError: is not a constructor in Jest.mock

girish TS picture girish TS · Feb 21, 2019 · Viewed 8.7k times · Source

I am trying to write a unit test case using jest and need to mock the below pattern . I am getting TypeError: is not a constructor.

Usecase : My usecase is as mentioned below

MyComponent.js :

 import serviceRegistry from "external/serviceRegistry";


        serviceRegistry.getService("modulename", "servvice").then(
              service => {
                let myServiceInstance = new service();
                myServiceInstance.init(p,d) 
        })

Mycomponent.spec.js

jest.mock('external/serviceRegistry', () => {
      return {
        getService: jest.fn(() => Promise.resolve({
          service: jest.fn().mockImplementation((properties, data, contribs) => {
            return {
              init: jest.fn(),
              util: jest.fn(),
              aspect: jest.fn()

            };
          })
        }))
      };
    }, {virtual: true});

Answer

Brian Adams picture Brian Adams · Feb 21, 2019

The Promise returned by getService is resolving to an object with a service prop set to your constructor mock, but your code is expecting it to resolve directly to your constructor mock.

Change your external/serviceRegistry mock to this and it should work:

jest.mock('external/serviceRegistry', () => {
  return {
    getService: jest.fn(() => Promise.resolve(
      jest.fn().mockImplementation((properties, data, contribs) => {
        return {
          init: jest.fn(),
          util: jest.fn(),
          aspect: jest.fn()
        };
      })
    ))
  };
}, {virtual: true});