test(auth,payments,subs): add 58 unit tests for critical auth, payment, and subscription paths

Cover auth handlers (RegisterUser, LoginUser, RefreshToken), TokenService
(token rotation, reuse attack detection), payment callback edge cases
(duplicate/concurrent callbacks, multi-provider), subscription lifecycle
transitions (expire, pastDue, renew), and throttler proxy guard.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Ho Ngoc Hai
2026-04-08 13:49:19 +07:00
parent a590a41e73
commit bac3313873
13 changed files with 1031 additions and 0 deletions

View File

@@ -0,0 +1,52 @@
import { LoginUserCommand } from '../commands/login-user/login-user.command';
import { LoginUserHandler } from '../commands/login-user/login-user.handler';
describe('LoginUserHandler', () => {
let handler: LoginUserHandler;
let mockTokenService: { generateTokenPair: ReturnType<typeof vi.fn> };
const tokenPair = {
accessToken: 'access-jwt',
refreshToken: 'family.refresh-hex',
expiresIn: 900,
};
beforeEach(() => {
mockTokenService = { generateTokenPair: vi.fn().mockResolvedValue(tokenPair) };
handler = new LoginUserHandler(mockTokenService as any);
});
it('generates token pair with correct payload', async () => {
const command = new LoginUserCommand('user-1', '0912345678', 'BUYER');
const result = await handler.execute(command);
expect(result).toEqual(tokenPair);
expect(mockTokenService.generateTokenPair).toHaveBeenCalledWith({
sub: 'user-1',
phone: '0912345678',
role: 'BUYER',
});
});
it('passes AGENT role correctly', async () => {
const command = new LoginUserCommand('user-2', '0987654321', 'AGENT');
await handler.execute(command);
expect(mockTokenService.generateTokenPair).toHaveBeenCalledWith({
sub: 'user-2',
phone: '0987654321',
role: 'AGENT',
});
});
it('passes ADMIN role correctly', async () => {
const command = new LoginUserCommand('admin-1', '0901234567', 'ADMIN');
await handler.execute(command);
expect(mockTokenService.generateTokenPair).toHaveBeenCalledWith({
sub: 'admin-1',
phone: '0901234567',
role: 'ADMIN',
});
});
});

View File

@@ -0,0 +1,122 @@
import { Phone } from '../../domain/value-objects/phone.vo';
import { UserEntity } from '../../domain/entities/user.entity';
import { HashedPassword } from '../../domain/value-objects/hashed-password.vo';
import { type IUserRepository } from '../../domain/repositories/user.repository';
import { RefreshTokenCommand } from '../commands/refresh-token/refresh-token.command';
import { RefreshTokenHandler } from '../commands/refresh-token/refresh-token.handler';
function createActiveUser(): UserEntity {
const phone = Phone.create('0912345678').unwrap();
const pw = { value: 'hashed' } as HashedPassword;
return new UserEntity('user-1', {
email: null,
phone,
passwordHash: pw,
fullName: 'Test User',
avatarUrl: null,
role: 'BUYER',
kycStatus: 'NONE',
kycData: null,
isActive: true,
});
}
function createInactiveUser(): UserEntity {
const phone = Phone.create('0912345678').unwrap();
const pw = { value: 'hashed' } as HashedPassword;
return new UserEntity('user-1', {
email: null,
phone,
passwordHash: pw,
fullName: 'Deactivated User',
avatarUrl: null,
role: 'BUYER',
kycStatus: 'NONE',
kycData: null,
isActive: false,
});
}
describe('RefreshTokenHandler', () => {
let handler: RefreshTokenHandler;
let mockTokenService: {
rotateRefreshToken: ReturnType<typeof vi.fn>;
generateAccessToken: ReturnType<typeof vi.fn>;
};
let mockUserRepo: { [K in keyof IUserRepository]: ReturnType<typeof vi.fn> };
beforeEach(() => {
mockTokenService = {
rotateRefreshToken: vi.fn(),
generateAccessToken: vi.fn().mockReturnValue('new-access-jwt'),
};
mockUserRepo = {
findById: vi.fn(),
findByPhone: vi.fn(),
findByEmail: vi.fn(),
save: vi.fn(),
update: vi.fn(),
};
handler = new RefreshTokenHandler(
mockTokenService as any,
mockUserRepo as any,
);
});
it('rotates refresh token and returns new token pair', async () => {
mockTokenService.rotateRefreshToken.mockResolvedValue({
userId: 'user-1',
refreshToken: 'new-family.new-refresh-hex',
});
mockUserRepo.findById.mockResolvedValue(createActiveUser());
const command = new RefreshTokenCommand('old-family.old-refresh-hex');
const result = await handler.execute(command);
expect(result.accessToken).toBe('new-access-jwt');
expect(result.refreshToken).toBe('new-family.new-refresh-hex');
expect(result.expiresIn).toBe(900);
expect(mockTokenService.generateAccessToken).toHaveBeenCalledWith(
expect.objectContaining({ sub: 'user-1', phone: '+84912345678', role: 'BUYER' }),
);
});
it('throws UnauthorizedException when refresh token is invalid', async () => {
mockTokenService.rotateRefreshToken.mockResolvedValue(null);
const command = new RefreshTokenCommand('invalid-token');
await expect(handler.execute(command)).rejects.toThrow(
'Refresh token không hợp lệ hoặc đã hết hạn',
);
});
it('throws UnauthorizedException when user not found', async () => {
mockTokenService.rotateRefreshToken.mockResolvedValue({
userId: 'deleted-user',
refreshToken: 'new-family.new-hex',
});
mockUserRepo.findById.mockResolvedValue(null);
const command = new RefreshTokenCommand('family.valid-hex');
await expect(handler.execute(command)).rejects.toThrow(
'Tài khoản không tồn tại hoặc đã bị vô hiệu hóa',
);
});
it('throws UnauthorizedException when user is deactivated', async () => {
mockTokenService.rotateRefreshToken.mockResolvedValue({
userId: 'user-1',
refreshToken: 'new-family.new-hex',
});
mockUserRepo.findById.mockResolvedValue(createInactiveUser());
const command = new RefreshTokenCommand('family.valid-hex');
await expect(handler.execute(command)).rejects.toThrow(
'Tài khoản không tồn tại hoặc đã bị vô hiệu hóa',
);
});
});

View File

@@ -0,0 +1,106 @@
import { type IUserRepository } from '../../domain/repositories/user.repository';
import { Phone } from '../../domain/value-objects/phone.vo';
import { RegisterUserCommand } from '../commands/register-user/register-user.command';
import { RegisterUserHandler } from '../commands/register-user/register-user.handler';
describe('RegisterUserHandler', () => {
let handler: RegisterUserHandler;
let mockUserRepo: { [K in keyof IUserRepository]: ReturnType<typeof vi.fn> };
let mockTokenService: { generateTokenPair: ReturnType<typeof vi.fn> };
let mockEventBus: { publish: ReturnType<typeof vi.fn> };
const tokenPair = {
accessToken: 'access-jwt',
refreshToken: 'family.refresh-hex',
expiresIn: 900,
};
beforeEach(() => {
mockUserRepo = {
findById: vi.fn(),
findByPhone: vi.fn().mockResolvedValue(null),
findByEmail: vi.fn().mockResolvedValue(null),
save: vi.fn().mockResolvedValue(undefined),
update: vi.fn(),
};
mockTokenService = { generateTokenPair: vi.fn().mockResolvedValue(tokenPair) };
mockEventBus = { publish: vi.fn() };
handler = new RegisterUserHandler(
mockUserRepo as any,
mockTokenService as any,
mockEventBus as any,
);
});
it('registers a new user and returns token pair', async () => {
const command = new RegisterUserCommand('0912345678', 'StrongP@ss1', 'Nguyen Van A');
const result = await handler.execute(command);
expect(result).toEqual(tokenPair);
expect(mockUserRepo.save).toHaveBeenCalledTimes(1);
expect(mockTokenService.generateTokenPair).toHaveBeenCalledWith(
expect.objectContaining({ phone: '+84912345678', role: 'BUYER' }),
);
expect(mockEventBus.publish).toHaveBeenCalled();
});
it('registers user with optional email', async () => {
const command = new RegisterUserCommand(
'0912345678', 'StrongP@ss1', 'Nguyen Van A', 'test@example.com',
);
const result = await handler.execute(command);
expect(result).toEqual(tokenPair);
expect(mockUserRepo.findByEmail).toHaveBeenCalledWith('test@example.com');
expect(mockUserRepo.save).toHaveBeenCalledTimes(1);
});
it('throws ConflictException when phone already exists', async () => {
mockUserRepo.findByPhone.mockResolvedValue({ id: 'existing-user' });
const command = new RegisterUserCommand('0912345678', 'StrongP@ss1', 'Nguyen Van A');
await expect(handler.execute(command)).rejects.toThrow('Số điện thoại đã được đăng ký');
});
it('throws ConflictException when email already exists', async () => {
mockUserRepo.findByEmail.mockResolvedValue({ id: 'existing-user' });
const command = new RegisterUserCommand(
'0912345678', 'StrongP@ss1', 'Nguyen Van A', 'taken@example.com',
);
await expect(handler.execute(command)).rejects.toThrow('Email đã được đăng ký');
});
it('throws ValidationException for invalid phone number', async () => {
const command = new RegisterUserCommand('12345', 'StrongP@ss1', 'Nguyen Van A');
await expect(handler.execute(command)).rejects.toThrow();
});
it('throws ValidationException for invalid email format', async () => {
const command = new RegisterUserCommand(
'0912345678', 'StrongP@ss1', 'Nguyen Van A', 'not-an-email',
);
await expect(handler.execute(command)).rejects.toThrow();
});
it('publishes UserRegisteredEvent after saving', async () => {
const command = new RegisterUserCommand('0912345678', 'StrongP@ss1', 'Nguyen Van A');
await handler.execute(command);
expect(mockEventBus.publish).toHaveBeenCalledWith(
expect.objectContaining({ eventName: 'user.registered' }),
);
});
it('does not save user if phone validation fails', async () => {
const command = new RegisterUserCommand('invalid', 'StrongP@ss1', 'Nguyen Van A');
await expect(handler.execute(command)).rejects.toThrow();
expect(mockUserRepo.save).not.toHaveBeenCalled();
});
});