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 :
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});
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.
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});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With