Jest TypeError:不是Jest.mock中的构造函数 [英] Jest TypeError: is not a constructor in Jest.mock
问题描述
我正在尝试使用Jest编写单元测试用例,并且需要模拟以下模式.我收到TypeError:不是构造函数.
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:
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
正在解析为object
,并且为构造函数模型设置了service
道具,但是您的代码期望它可以直接解析为您的构造函数模型.
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屋!