Jest TypeError:不是Jest.mock中的构造函数

时间:2019-02-21 13:09:46

标签: reactjs jestjs babel-jest jest-fetch-mock

我正在尝试使用Jest编写单元测试用例,并且需要模拟以下模式。我收到TypeError:不是构造函数。

用例:我的用例如下所述

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 个答案:

答案 0 :(得分:1)

Promise返回的getService解析为一个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});