I’m new to Jest and currently writing a Typescript NodeJS API. Jest allows me to do all my tests, but there is still one case I can’t achieve :
I have an Email.ts service class that contains methods just like this
export default class Email {
// constructor and logic, takes some unique infos to params the email properly
// some methods like this
async sendWelcome(): Promise<void> {
await this.send("welcome", "Bienvenue !"); // get an html template and send the email
}
}
And inside my controllers, I sometimes send an email. Exemple :
export const authController: IController = {
// some methods
registerConfirm: async (req, res, next) => {
// some logic
await new Email(// user infos and stuff to send email to).sendWelcome();
}
}
Now inside my test file, I try to see if during my API call, the method sendWelcome() was called, but I can’t find how to write this… Here is my test
describe("with all valid fields", () => {
it("should return a CREATED 201 response", async () => {
const reqBody = {
password: "pass1234",
passwordConfirm: "pass1234*",
};
// making the request that should call the authController method shown before, that calls the new Email().sendWelcome() method
const res = await request(app)
.post(`/api/v1/auth/register-confirm/${testProvUser._id}`)
.send(reqBody);
const provUserInDb = await ProvisionalUser.findOne({
email: testProvUser.email,
});
const userInDb = await User.findOne({
email: testProvUser.email,
});
expect(provUserInDb).toEqual(null);
expect(userInDb).not.toEqual(null);
testResponseBody(
res,
"success",
201,
`/api/v1/auth/register-confirm/${testProvUser._id}`,
true,
"POST"
);
});
});
I tried to mock the whole Email class like specified in the official documentation, but I can’t get access to the new instance (new Email()) created inside the controller method to see if the method has been called on it.
I tried to use spyOn method from Jest, but here again I can’t access to the new instance from my test file…
I have to create unique instance in each case to adapt the Email params (like the send to field).
Any idea how to test this ?
Thanks a lot in advance !