Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest TypeError: is not a constructor in Jest.mock

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});
like image 659
girish TS Avatar asked Oct 16 '22 06:10

girish TS


1 Answers

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});
like image 189
Brian Adams Avatar answered Oct 21 '22 02:10

Brian Adams