I have this twilio.service.ts
file. I want to write a unit test in twilio.service.spec.ts
for two cases in which the verification OTP has been sent successfully or failed with missing parameters.
twilio.services.ts:
async startVerification(
startVerificationDto: StartVerificationDto
) {
try {
const verificationResponse = await this.twilioClient.verify
.services("TWILIO_VERIFY_SERVICE_SID")
.verifications.create({
to: `+91${sendVerificationCodeDto.phoneNumber}`,
channel: "sms",
locale: "en",
});
return verificationResponse;
} catch (error) {
throw new BadRequestException("Failed sending OTP");
}
}
It tried so far:
it("Should be able to send verification code on mobile number", async () => {
const actualRes = await controller.startVerification({
phoneNumber: "xxxxxxxxxxx",
});
expect(twilioService.twilioClient.verify.services).toBeCalledWith(
"TWILIO_VERIFY_SERVICE_SID"
);
expect(actualRes).toEqual({
sid: "VA_TWILIO_VERIFY_SERVICE_SID",
});
});
it("Should return error if required parameters are missing", async () => {
expect(twilioService.twilioClient.verify.services).not.toBeCalledWith(
"TWILIO_VERIFY_SERVICE_SID"
);
try {
await controller.startVerification({
phoneNumber: "xxxxxxxxxxx",
});
} catch (e) {
expect(e.message).toBe("Failed sending OTP");
}
});
My main concern is: how to mock nested functions of Twilio (verify>service>verification>create). Also, after mocking how do I call or use that in spec.ts file.