Jest TypeError: is not a constructor in Jest.mock

Jest TypeError: is not a constructor in Jest.mock

我正在尝试使用 jest 编写单元测试用例,需要模拟以下模式。我收到 TypeError: is not a constructor.

用例:我的用例如下所述

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

getService 返回的 Promise 正在解析为 object,其中 service 道具设置为您的构造函数模拟,但您的代码期望它直接解析给你的构造函数模拟。

将您的 external/serviceRegistry 模拟更改为此,它应该可以工作:

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