Files
canina/backend/src/users/users.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

197 lines
6.6 KiB
TypeScript

import { Test, TestingModule } from "@nestjs/testing";
import { UsersService } from "./users.service";
import { PrismaService } from "../prisma/prisma.service";
import { BadRequestException, NotFoundException } from "@nestjs/common";
import * as bcrypt from "bcryptjs";
describe("UsersService", () => {
let service: UsersService;
let prisma: PrismaService;
const mockPrisma = {
user: {
findUnique: jest.fn(),
update: jest.fn(),
},
userAddress: {
updateMany: jest.fn(),
create: jest.fn(),
update: jest.fn(),
delete: jest.fn(),
},
};
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
UsersService,
{ provide: PrismaService, useValue: mockPrisma },
],
}).compile();
service = module.get<UsersService>(UsersService);
prisma = module.get<PrismaService>(PrismaService);
});
afterEach(() => {
jest.clearAllMocks();
});
it("should be defined", () => {
expect(service).toBeDefined();
});
describe("findById", () => {
it("should return null when user does not exist", async () => {
mockPrisma.user.findUnique.mockResolvedValue(null);
const res = await service.findById("missing-id");
expect(res).toBeNull();
});
it("should return safe user profile hiding password hash but indicating hasPassword", async () => {
mockPrisma.user.findUnique.mockResolvedValue({
id: "u-1",
mobile: "09121111111",
password: "hashed-password-string",
firstName: "Parsa",
});
const res = await service.findById("u-1");
expect(res).not.toHaveProperty("password");
expect(res?.hasPassword).toBe(true);
expect(res?.firstName).toBe("Parsa");
});
});
describe("update profile & security checks", () => {
it("should throw NotFoundException if user is not found", async () => {
mockPrisma.user.findUnique.mockResolvedValue(null);
await expect(
service.update("u-missing", { firstName: "Test" }),
).rejects.toThrow(NotFoundException);
});
it("should throw BadRequestException if new mobile is already taken by another user", async () => {
mockPrisma.user.findUnique
.mockResolvedValueOnce({ id: "u-1", mobile: "09121111111" }) // current user
.mockResolvedValueOnce({ id: "u-2", mobile: "09122222222" }); // conflict user
await expect(
service.update("u-1", { mobile: "09122222222" }),
).rejects.toThrow("این شماره موبایل قبلاً توسط کاربر دیگری ثبت شده است");
});
it("should throw BadRequestException if new email is already taken by another user", async () => {
mockPrisma.user.findUnique
.mockResolvedValueOnce({ id: "u-1", email: "user1@canina.ir" }) // current user
.mockResolvedValueOnce({ id: "u-2", email: "conflict@canina.ir" }); // conflict user
await expect(
service.update("u-1", { email: "conflict@canina.ir" }),
).rejects.toThrow("این آدرس ایمیل قبلاً توسط کاربر دیگری ثبت شده است");
});
it("should require currentPassword if user already has password set and attempts password change", async () => {
mockPrisma.user.findUnique.mockResolvedValue({
id: "u-1",
password: "existing-hash",
});
await expect(
service.update("u-1", { password: "new-strong-password" }),
).rejects.toThrow(
"برای تغییر رمز عبور، وارد کردن رمز عبور فعلی الزامی است",
);
});
it("should reject password update if currentPassword does not match existing password", async () => {
const hashedOld = await bcrypt.hash("correct-old-password", 10);
mockPrisma.user.findUnique.mockResolvedValue({
id: "u-1",
password: hashedOld,
});
await expect(
service.update("u-1", {
currentPassword: "wrong-password",
password: "new-strong-password",
}),
).rejects.toThrow("رمز عبور فعلی اشتباه است");
});
it("should update password and return safe user when currentPassword matches", async () => {
const hashedOld = await bcrypt.hash("correct-old-password", 10);
mockPrisma.user.findUnique.mockResolvedValue({
id: "u-1",
password: hashedOld,
});
mockPrisma.user.update.mockResolvedValue({
id: "u-1",
firstName: "Parsa",
password: "new-hashed-password",
});
const res = await service.update("u-1", {
currentPassword: "correct-old-password",
password: "new-password-123",
});
expect(res).not.toHaveProperty("password");
expect(res?.hasPassword).toBe(true);
expect(mockPrisma.user.update).toHaveBeenCalled();
});
});
describe("address management", () => {
it("should addAddress and unset previous default addresses if isDefault is true", async () => {
const addressData = {
title: "Home",
receptorName: "Parsa",
phone: "09121111111",
province: "Tehran",
city: "Tehran",
detail: "Street 1",
zipCode: "1234567890",
isDefault: true,
};
mockPrisma.userAddress.create.mockResolvedValue({
id: "addr-id",
...addressData,
});
const result = await service.addAddress("user-id", addressData);
expect(prisma.userAddress.updateMany).toHaveBeenCalledWith({
where: { userId: "user-id" },
data: { isDefault: false },
});
expect(prisma.userAddress.create).toHaveBeenCalled();
expect(result.id).toBe("addr-id");
});
it("should deleteAddress ensuring scoped by userId", async () => {
mockPrisma.userAddress.delete.mockResolvedValue({ id: "addr-id" });
const result = await service.deleteAddress("user-id", "addr-id");
expect(prisma.userAddress.delete).toHaveBeenCalledWith({
where: { id: "addr-id", userId: "user-id" },
});
expect(result.id).toBe("addr-id");
});
it("should setDefaultAddress by clearing others and updating target", async () => {
mockPrisma.userAddress.update.mockResolvedValue({
id: "addr-id",
isDefault: true,
});
const result = await service.setDefaultAddress("user-id", "addr-id");
expect(prisma.userAddress.updateMany).toHaveBeenCalledWith({
where: { userId: "user-id" },
data: { isDefault: false },
});
expect(prisma.userAddress.update).toHaveBeenCalledWith({
where: { id: "addr-id", userId: "user-id" },
data: { isDefault: true },
});
expect(result.isDefault).toBe(true);
});
});
});