Jest TypeError: 不是 Jest.mock 中的构造函数 [英] Jest TypeError: is not a constructor in Jest.mock

查看:40
本文介绍了Jest TypeError: 不是 Jest.mock 中的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

用例:我的用例如下

MyComponent.js :

MyComponent.js :

 import serviceRegistry from "external/serviceRegistry";


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

Mycomponent.spec.js

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 正在解析为带有service prop 设置为您的构造函数模拟,但您的代码期望它直接解析为您的构造函数模拟.

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.

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

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

这篇关于Jest TypeError: 不是 Jest.mock 中的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆