Files
gridpilot.gg/core/identity/application/use-cases/LoginUseCase.test.ts
2025-12-20 12:55:07 +01:00

82 lines
2.5 KiB
TypeScript

import { describe, it, expect, vi, type Mock } from 'vitest';
import { LoginUseCase } from './LoginUseCase';
import { EmailAddress } from '../../domain/value-objects/EmailAddress';
import type { IAuthRepository } from '../../domain/repositories/IAuthRepository';
import type { IPasswordHashingService } from '../../domain/services/PasswordHashingService';
import { User } from '../../domain/entities/User';
describe('LoginUseCase', () => {
let authRepo: {
findByEmail: Mock;
};
let passwordService: {
verify: Mock;
};
let useCase: LoginUseCase;
beforeEach(() => {
authRepo = {
findByEmail: vi.fn(),
};
passwordService = {
verify: vi.fn(),
};
useCase = new LoginUseCase(
authRepo as unknown as IAuthRepository,
passwordService as unknown as IPasswordHashingService,
);
});
it('returns the user when credentials are valid', async () => {
const email = 'test@example.com';
const password = 'password123';
const emailVO = EmailAddress.create(email);
const user = User.create({
id: { value: 'user-1' } as any,
displayName: 'Test User',
email: emailVO.value,
});
(user as any).getPasswordHash = () => ({ value: 'stored-hash' });
authRepo.findByEmail.mockResolvedValue(user);
passwordService.verify.mockResolvedValue(true);
const result = await useCase.execute(email, password);
expect(authRepo.findByEmail).toHaveBeenCalledWith(emailVO);
expect(passwordService.verify).toHaveBeenCalledWith(password, 'stored-hash');
expect(result).toBe(user);
});
it('throws when user is not found', async () => {
const email = 'missing@example.com';
authRepo.findByEmail.mockResolvedValue(null);
await expect(useCase.execute(email, 'password')).rejects.toThrow('Invalid credentials');
});
it('throws when password is invalid', async () => {
const email = 'test@example.com';
const password = 'wrong-password';
const emailVO = EmailAddress.create(email);
const user = User.create({
id: { value: 'user-1' } as any,
displayName: 'Test User',
email: emailVO.value,
});
(user as any).getPasswordHash = () => ({ value: 'stored-hash' });
authRepo.findByEmail.mockResolvedValue(user);
passwordService.verify.mockResolvedValue(false);
await expect(useCase.execute(email, password)).rejects.toThrow('Invalid credentials');
expect(authRepo.findByEmail).toHaveBeenCalled();
expect(passwordService.verify).toHaveBeenCalled();
});
});