我正在尝试使用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});
答案 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});