Jest TypeError: is not a constructor in Jest.mock

久未见 提交于 2020-07-10 12:11:34

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/54807916/jest-typeerror-is-not-a-constructor-in-jest-mock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!