-
Notifications
You must be signed in to change notification settings - Fork 1.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Issue while (unit test) mocking container.get service #32
Comments
In the unit test code, you don't have to use Container nor the @service or @Inject decorators. The idea is that you mock every dependency of the class that you are going to test. Also, you don't necessarily need to write a Class for the mock, just use a normal object with the involved functions mocked with jest describe('Account', () => {
describe('#deviceChange', () => {
it('check everyting cool', async done => {
let logger = {};
let otpModel = {
updateOTPtoInactiveForModule: jest
.fn()
.mockImplementation(async(deviceChange : string, accountId : number) => new Promise((resolve : any) => resolve(true))),
getUserPhoneService: jest
.fn()
.mockResolvedValue(true)
};
let devicechangeModel = {
addDeviceChangeDetails: jest
.fn()
.mockResolvedValue(true),
updateDeviceChangeToInactive: jest
.fn()
.mockResolvedValue(true)
};
let DeviceChangeServiceInstance = new DeviceChangeService(devicechangeModel, otpModel, logger);
let deviceChangeStatus = DeviceChangeServiceInstance.deviceChange(accountId, deviceId, newdeviceId, created, mobile);
});
});
}); Now the problem that I see in your code is that you are using the service locator to obtain a dependency that should be injected into the constructor. So, what I'm saying is that you need to change this let OTPServiceInstance = Container.get(OTPService); For this constructor(
@Inject('devicechangeModel')private devicechangeModel,
@Inject('otpModel')private otpModel,
@Inject('logger')private logger,
@Inject() private OTPServiceInstance: OTPService, // Here is injected.
) {
} The function Container.get (formal name 'Service Locator') should only be used in the entry point of the code execution What do you think? |
Hello santiq, Sorry for the delay, but as per ur instructions, i implemented it and works perfectly, and checked out other git repo like many have implemented the same way you have guided. Thanks satiq, |
Hello santiq,
I am back again:-)!. Hey i am having issues in unit testing container.get(service), checkout the below code.
Here i am not able to set mock class for OTPService, so not able to alter container.get(OTPService) from the above code.
I have tried below but still it does'nt come inside mocked service.
Guys any idea how to solve this...
The text was updated successfully, but these errors were encountered: