我正在尝试使用开玩笑编写单元测试案例,需要模拟以下模式。我正在得到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});
getService
返回的 Promise
正在解决 object
,其中 service
prop设置为构造函数模拟,但是您的代码期望它直接解析为构造函数模拟。
将您的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});