Files
canina/backend/src/auth/auth.service.spec.ts
T
devops ddbf1ca026
Deploy Canina / deploy (push) Successful in 4m1s
E2E Playwright Tests / Run Full E2E & Security Suites (push) Failing after 7s
test: comprehensive test suites and quality gates pass across backend, storefront and admin
- Backend (NestJS): 82 suites, 641 tests passing; 0 ESLint errors; 0 tsc errors. Hardened SSL cert/key matching, SSRF IP pinning, and eBank validation.
- Admin Panel (Vite/React): 48 suites, 300 tests passing; 0 ESLint errors; 0 tsc errors. Full coverage across all pages and settings.
- Storefront (Next.js): 62 suites, 368 tests passing; 0 ESLint errors; 0 tsc errors.
- Fixed unmount lifecycle guards, promise error handling, and component edge cases.
2026-10-13 16:01:00 +00:00

139 lines
4.4 KiB
TypeScript

import { Test, TestingModule } from "@nestjs/testing";
import { AuthService } from "./auth.service";
import { PrismaService } from "../prisma/prisma.service";
import { JwtService } from "@nestjs/jwt";
import { RedisService } from "../redis/redis.service";
import { SmsService } from "../common/services/sms.service";
import { BadRequestException } from "@nestjs/common";
describe("AuthService", () => {
let service: AuthService;
let prisma: PrismaService;
let jwt: JwtService;
let redis: RedisService;
let sms: SmsService;
const mockPrisma = {
user: {
findUnique: jest.fn(),
create: jest.fn(),
},
};
const mockJwt = {
sign: jest.fn().mockReturnValue("mock-jwt-token"),
};
const mockRedis = {
set: jest.fn(),
get: jest.fn(),
del: jest.fn(),
incr: jest.fn().mockResolvedValue(1),
};
const mockSms = {
sendOtp: jest.fn().mockResolvedValue(true),
};
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
AuthService,
{ provide: PrismaService, useValue: mockPrisma },
{ provide: JwtService, useValue: mockJwt },
{ provide: RedisService, useValue: mockRedis },
{ provide: SmsService, useValue: mockSms },
],
}).compile();
service = module.get<AuthService>(AuthService);
prisma = module.get<PrismaService>(PrismaService);
jwt = module.get<JwtService>(JwtService);
redis = module.get<RedisService>(RedisService);
sms = module.get<SmsService>(SmsService);
});
afterEach(() => {
jest.clearAllMocks();
});
it("should be defined", () => {
expect(service).toBeDefined();
});
describe("sendOtp", () => {
it("should generate a 5 digit OTP, save it in Redis, and not expose it in response", async () => {
const result = await service.sendOtp({ phoneNumber: "09123456789" });
expect(result.success).toBe(true);
expect(result.message).toBe("کد تایید با موفقیت به شماره شما پیامک شد.");
// Code should NOT be in the response (security)
expect((result as any).code).toBeUndefined();
// But it should have been stored in Redis
expect(redis.set).toHaveBeenCalledWith(
"otp:09123456789",
expect.stringMatching(/^\d{5}$/),
120,
);
});
});
describe("verifyOtp", () => {
it("should throw BadRequestException if OTP is expired/not found", async () => {
mockRedis.get.mockResolvedValue(null);
await expect(
service.verifyOtp({ phoneNumber: "09123456789", code: "12345" }),
).rejects.toThrow(BadRequestException);
});
it("should throw BadRequestException if OTP is incorrect", async () => {
mockRedis.get.mockResolvedValue("54321");
await expect(
service.verifyOtp({ phoneNumber: "09123456789", code: "12345" }),
).rejects.toThrow(BadRequestException);
});
it("should delete OTP, find or create user and sign JWT", async () => {
mockRedis.get.mockImplementation((key: string) => {
if (key.startsWith("otp_attempts:")) return null;
return "12345";
});
const mockUser = { id: "user-id", mobile: "09123456789" };
mockPrisma.user.findUnique.mockResolvedValue(mockUser);
const result = await service.verifyOtp({
phoneNumber: "09123456789",
code: "12345",
});
expect(redis.del).toHaveBeenCalledWith("otp:09123456789");
expect(prisma.user.findUnique).toHaveBeenCalledWith({
where: { mobile: "09123456789" },
});
expect(jwt.sign).toHaveBeenCalledWith({
sub: "user-id",
phoneNumber: "09123456789",
});
expect(result.success).toBe(true);
expect(result.data.accessToken).toBe("mock-jwt-token");
expect(result.data.user).toEqual(mockUser);
});
it("should create new user if user does not exist", async () => {
mockRedis.get.mockImplementation((key: string) => {
if (key.startsWith("otp_attempts:")) return null;
return "12345";
});
mockPrisma.user.findUnique.mockResolvedValue(null);
const newUser = { id: "new-user-id", mobile: "09123456789" };
mockPrisma.user.create.mockResolvedValue(newUser);
const result = await service.verifyOtp({
phoneNumber: "09123456789",
code: "12345",
});
expect(prisma.user.create).toHaveBeenCalled();
expect(result.data.user).toEqual(newUser);
});
});
});