refactor use cases
This commit is contained in:
@@ -1,15 +1,18 @@
|
||||
import { describe, it, expect, vi, type Mock } from 'vitest';
|
||||
import {
|
||||
LoginWithEmailUseCase,
|
||||
type LoginWithEmailInput,
|
||||
type LoginWithEmailResult,
|
||||
type LoginWithEmailErrorCode,
|
||||
} from './LoginWithEmailUseCase';
|
||||
import type { IUserRepository, StoredUser } from '../../domain/repositories/IUserRepository';
|
||||
import { describe, it, expect, vi, type Mock, beforeEach } from 'vitest';
|
||||
import { LoginWithEmailUseCase } from './LoginWithEmailUseCase';
|
||||
import type { IUserRepository } from '../../domain/repositories/IUserRepository';
|
||||
import type { IdentitySessionPort } from '../ports/IdentitySessionPort';
|
||||
import type { UseCaseOutputPort, Logger } from '@core/shared/application';
|
||||
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
|
||||
import { Result } from '@core/shared/application/Result';
|
||||
import type { Logger } from '@core/shared/application';
|
||||
|
||||
// Mock the PasswordHash module
|
||||
vi.mock('@core/identity/domain/value-objects/PasswordHash', () => ({
|
||||
PasswordHash: {
|
||||
fromHash: vi.fn((hash: string) => ({
|
||||
verify: vi.fn().mockResolvedValue(hash === 'hashed-password'),
|
||||
value: hash,
|
||||
})),
|
||||
},
|
||||
}));
|
||||
|
||||
describe('LoginWithEmailUseCase', () => {
|
||||
let userRepository: {
|
||||
@@ -17,169 +20,119 @@ describe('LoginWithEmailUseCase', () => {
|
||||
};
|
||||
let sessionPort: {
|
||||
createSession: Mock;
|
||||
getCurrentSession: Mock;
|
||||
clearSession: Mock;
|
||||
};
|
||||
let logger: Logger & { error: Mock };
|
||||
let output: UseCaseOutputPort<LoginWithEmailResult> & { present: Mock };
|
||||
let logger: Logger;
|
||||
let useCase: LoginWithEmailUseCase;
|
||||
|
||||
beforeEach(() => {
|
||||
userRepository = {
|
||||
findByEmail: vi.fn(),
|
||||
};
|
||||
|
||||
sessionPort = {
|
||||
createSession: vi.fn(),
|
||||
getCurrentSession: vi.fn(),
|
||||
clearSession: vi.fn(),
|
||||
};
|
||||
|
||||
logger = {
|
||||
debug: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
} as unknown as Logger & { error: Mock };
|
||||
output = {
|
||||
present: vi.fn(),
|
||||
} as unknown as UseCaseOutputPort<LoginWithEmailResult> & { present: Mock };
|
||||
} as unknown as Logger;
|
||||
|
||||
useCase = new LoginWithEmailUseCase(
|
||||
userRepository as unknown as IUserRepository,
|
||||
sessionPort as unknown as IdentitySessionPort,
|
||||
logger,
|
||||
output,
|
||||
);
|
||||
});
|
||||
|
||||
it('returns ok and presents session result for valid credentials', async () => {
|
||||
const input: LoginWithEmailInput = {
|
||||
email: 'Test@Example.com',
|
||||
password: 'password123',
|
||||
};
|
||||
|
||||
// Import PasswordHash to create a proper hash
|
||||
const { PasswordHash } = await import('@core/identity/domain/value-objects/PasswordHash');
|
||||
const passwordHash = await PasswordHash.create('password123');
|
||||
|
||||
const storedUser: StoredUser = {
|
||||
const storedUser = {
|
||||
id: 'user-1',
|
||||
email: 'test@example.com',
|
||||
displayName: 'Test User',
|
||||
passwordHash: passwordHash.value,
|
||||
displayName: 'John Smith',
|
||||
passwordHash: 'hashed-password',
|
||||
createdAt: new Date(),
|
||||
};
|
||||
|
||||
const session = {
|
||||
userRepository.findByEmail.mockResolvedValue(storedUser);
|
||||
sessionPort.createSession.mockResolvedValue({
|
||||
token: 'token-123',
|
||||
user: {
|
||||
id: storedUser.id,
|
||||
email: storedUser.email,
|
||||
displayName: storedUser.displayName,
|
||||
id: 'user-1',
|
||||
email: 'test@example.com',
|
||||
displayName: 'John Smith',
|
||||
},
|
||||
issuedAt: Date.now(),
|
||||
expiresAt: Date.now() + 1000,
|
||||
token: 'token-123',
|
||||
};
|
||||
|
||||
userRepository.findByEmail.mockResolvedValue(storedUser);
|
||||
sessionPort.createSession.mockResolvedValue(session);
|
||||
|
||||
const result: Result<void, ApplicationErrorCode<LoginWithEmailErrorCode, { message: string }>> =
|
||||
await useCase.execute(input);
|
||||
|
||||
expect(result.isOk()).toBe(true);
|
||||
expect(result.unwrap()).toBeUndefined();
|
||||
|
||||
expect(userRepository.findByEmail).toHaveBeenCalledWith('test@example.com');
|
||||
expect(sessionPort.createSession).toHaveBeenCalledWith({
|
||||
id: storedUser.id,
|
||||
displayName: storedUser.displayName,
|
||||
email: storedUser.email,
|
||||
});
|
||||
|
||||
expect(output.present).toHaveBeenCalledTimes(1);
|
||||
const presented = output.present.mock.calls[0]![0] as LoginWithEmailResult;
|
||||
expect(presented.sessionToken).toBe('token-123');
|
||||
expect(presented.userId).toBe(storedUser.id);
|
||||
expect(presented.displayName).toBe(storedUser.displayName);
|
||||
expect(presented.email).toBe(storedUser.email);
|
||||
const result = await useCase.execute({
|
||||
email: 'test@example.com',
|
||||
password: 'Password123',
|
||||
});
|
||||
|
||||
expect(result.isOk()).toBe(true);
|
||||
const loginResult = result.unwrap();
|
||||
expect(loginResult.sessionToken).toBe('token-123');
|
||||
expect(loginResult.userId).toBe('user-1');
|
||||
expect(loginResult.displayName).toBe('John Smith');
|
||||
expect(loginResult.email).toBe('test@example.com');
|
||||
expect(userRepository.findByEmail).toHaveBeenCalledWith('test@example.com');
|
||||
expect(sessionPort.createSession).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns INVALID_INPUT when email or password is missing', async () => {
|
||||
const result1 = await useCase.execute({ email: '', password: 'x' });
|
||||
const result2 = await useCase.execute({ email: 'a@example.com', password: '' });
|
||||
const result = await useCase.execute({
|
||||
email: '',
|
||||
password: 'Password123',
|
||||
});
|
||||
|
||||
expect(result1.isErr()).toBe(true);
|
||||
expect(result1.unwrapErr().code).toBe('INVALID_INPUT');
|
||||
expect(result2.isErr()).toBe(true);
|
||||
expect(result2.unwrapErr().code).toBe('INVALID_INPUT');
|
||||
expect(output.present).not.toHaveBeenCalled();
|
||||
expect(result.isErr()).toBe(true);
|
||||
expect(result.unwrapErr().code).toBe('INVALID_INPUT');
|
||||
});
|
||||
|
||||
it('returns INVALID_CREDENTIALS when user does not exist', async () => {
|
||||
const input: LoginWithEmailInput = {
|
||||
email: 'missing@example.com',
|
||||
password: 'password',
|
||||
};
|
||||
|
||||
userRepository.findByEmail.mockResolvedValue(null);
|
||||
|
||||
const result: Result<void, ApplicationErrorCode<LoginWithEmailErrorCode, { message: string }>> =
|
||||
await useCase.execute(input);
|
||||
const result = await useCase.execute({
|
||||
email: 'nonexistent@example.com',
|
||||
password: 'Password123',
|
||||
});
|
||||
|
||||
expect(result.isErr()).toBe(true);
|
||||
const error = result.unwrapErr();
|
||||
expect(error.code).toBe('INVALID_CREDENTIALS');
|
||||
expect(error.details.message).toBe('Invalid email or password');
|
||||
expect(output.present).not.toHaveBeenCalled();
|
||||
expect(result.unwrapErr().code).toBe('INVALID_CREDENTIALS');
|
||||
});
|
||||
|
||||
it('returns INVALID_CREDENTIALS when password is invalid', async () => {
|
||||
const input: LoginWithEmailInput = {
|
||||
email: 'test@example.com',
|
||||
password: 'wrong',
|
||||
};
|
||||
|
||||
// Create a hash for a different password
|
||||
const { PasswordHash } = await import('@core/identity/domain/value-objects/PasswordHash');
|
||||
const passwordHash = await PasswordHash.create('correct-password');
|
||||
|
||||
const storedUser: StoredUser = {
|
||||
const storedUser = {
|
||||
id: 'user-1',
|
||||
email: 'test@example.com',
|
||||
displayName: 'Test User',
|
||||
passwordHash: passwordHash.value,
|
||||
displayName: 'John Smith',
|
||||
passwordHash: 'wrong-hash', // Different hash to simulate wrong password
|
||||
createdAt: new Date(),
|
||||
};
|
||||
|
||||
userRepository.findByEmail.mockResolvedValue(storedUser);
|
||||
|
||||
const result: Result<void, ApplicationErrorCode<LoginWithEmailErrorCode, { message: string }>> =
|
||||
await useCase.execute(input);
|
||||
const result = await useCase.execute({
|
||||
email: 'test@example.com',
|
||||
password: 'WrongPassword',
|
||||
});
|
||||
|
||||
expect(result.isErr()).toBe(true);
|
||||
const error = result.unwrapErr();
|
||||
expect(error.code).toBe('INVALID_CREDENTIALS');
|
||||
expect(error.details.message).toBe('Invalid email or password');
|
||||
expect(output.present).not.toHaveBeenCalled();
|
||||
expect(result.unwrapErr().code).toBe('INVALID_CREDENTIALS');
|
||||
});
|
||||
|
||||
it('wraps unexpected errors as REPOSITORY_ERROR and logs them', async () => {
|
||||
const input: LoginWithEmailInput = {
|
||||
userRepository.findByEmail.mockRejectedValue(new Error('Database connection failed'));
|
||||
|
||||
const result = await useCase.execute({
|
||||
email: 'test@example.com',
|
||||
password: 'password123',
|
||||
};
|
||||
|
||||
userRepository.findByEmail.mockRejectedValue(new Error('DB failure'));
|
||||
|
||||
const result: Result<void, ApplicationErrorCode<LoginWithEmailErrorCode, { message: string }>> =
|
||||
await useCase.execute(input);
|
||||
password: 'Password123',
|
||||
});
|
||||
|
||||
expect(result.isErr()).toBe(true);
|
||||
const error = result.unwrapErr();
|
||||
|
||||
expect(error.code).toBe('REPOSITORY_ERROR');
|
||||
expect(error.details.message).toBe('DB failure');
|
||||
expect(output.present).not.toHaveBeenCalled();
|
||||
expect(result.unwrapErr().code).toBe('REPOSITORY_ERROR');
|
||||
expect(logger.error).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user