Files
memegoat/backend/src/mail/mail.service.spec.ts
Mathis HERRIOT 89bd9d65e7 feat: implement MailModule with email services and tests
Added MailModule with services for email validation and password reset functionalities. Includes configuration via `@nestjs-modules/mailer` and comprehensive unit tests.
2026-01-08 12:41:27 +01:00

88 lines
2.3 KiB
TypeScript

import { Logger } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { Test, TestingModule } from "@nestjs/testing";
import { MailerService } from "@nestjs-modules/mailer";
import { MailService } from "./mail.service";
describe("MailService", () => {
let service: MailService;
let mailerService: MailerService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
MailService,
{
provide: MailerService,
useValue: {
sendMail: jest.fn().mockResolvedValue({}),
},
},
{
provide: ConfigService,
useValue: {
get: jest.fn().mockReturnValue("test.io"),
},
},
],
}).compile();
service = module.get<MailService>(MailService);
mailerService = module.get<MailerService>(MailerService);
});
it("should be defined", () => {
expect(service).toBeDefined();
});
it("should send validation email with correct URL", async () => {
const email = "test@example.com";
const token = "token123";
await service.sendEmailValidation(email, token);
expect(mailerService.sendMail).toHaveBeenCalledWith(
expect.objectContaining({
to: email,
subject: "Validation de votre adresse email",
html: expect.stringContaining(
"https://test.io/api/auth/verify-email?token=token123",
),
}),
);
});
it("should send password reset email with correct URL", async () => {
const email = "test@example.com";
const token = "token123";
await service.sendPasswordReset(email, token);
expect(mailerService.sendMail).toHaveBeenCalledWith(
expect.objectContaining({
to: email,
subject: "Réinitialisation de votre mot de passe",
html: expect.stringContaining(
"https://test.io/api/auth/reset-password?token=token123",
),
}),
);
});
it("should throw and log error when sending fails", async () => {
const email = "test@example.com";
const token = "token123";
const error = new Error("SMTP Error");
(mailerService.sendMail as jest.Mock).mockRejectedValueOnce(error);
const loggerSpy = jest
.spyOn(Logger.prototype, "error")
.mockImplementation(() => {});
await expect(service.sendEmailValidation(email, token)).rejects.toThrow(
"SMTP Error",
);
expect(loggerSpy).toHaveBeenCalled();
loggerSpy.mockRestore();
});
});