Files
gridpilot.gg/core/identity/application/use-cases/SignupUseCase.test.ts
2026-01-08 15:34:51 +01:00

104 lines
3.0 KiB
TypeScript

import { describe, it, expect, vi, type Mock } from 'vitest';
import { SignupUseCase } from './SignupUseCase';
import type { IAuthRepository } from '../../domain/repositories/IAuthRepository';
import type { IPasswordHashingService } from '../../domain/services/PasswordHashingService';
import type { Logger } from '@core/shared/application';
import { User } from '../../domain/entities/User';
import { UserId } from '../../domain/value-objects/UserId';
import { PasswordHash } from '../../domain/value-objects/PasswordHash';
describe('SignupUseCase', () => {
let authRepo: {
findByEmail: Mock;
save: Mock;
};
let passwordService: {
hash: Mock;
};
let logger: Logger;
let useCase: SignupUseCase;
beforeEach(() => {
authRepo = {
findByEmail: vi.fn(),
save: vi.fn(),
};
passwordService = {
hash: vi.fn(),
};
logger = {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
} as unknown as Logger;
useCase = new SignupUseCase(
authRepo as unknown as IAuthRepository,
passwordService as unknown as IPasswordHashingService,
logger,
);
});
it('successfully signs up a new user', async () => {
authRepo.findByEmail.mockResolvedValue(null);
passwordService.hash.mockResolvedValue('hashed-password');
const result = await useCase.execute({
email: 'test@example.com',
password: 'Password123',
displayName: 'John Smith', // Valid name that passes validation
});
expect(result.isOk()).toBe(true);
const signupResult = result.unwrap();
expect(signupResult.user).toBeDefined();
expect(signupResult.user.getEmail()).toBe('test@example.com');
expect(signupResult.user.getDisplayName()).toBe('John Smith');
expect(authRepo.findByEmail).toHaveBeenCalledTimes(1);
expect(authRepo.save).toHaveBeenCalledTimes(1);
});
it('returns error when user already exists', async () => {
const existingUser = User.create({
id: UserId.create(),
displayName: 'John Smith',
email: 'test@example.com',
passwordHash: PasswordHash.fromHash('existing-hash'),
});
authRepo.findByEmail.mockResolvedValue(existingUser);
const result = await useCase.execute({
email: 'test@example.com',
password: 'Password123',
displayName: 'John Smith',
});
expect(result.isErr()).toBe(true);
expect(result.unwrapErr().code).toBe('USER_ALREADY_EXISTS');
});
it('returns error for weak password', async () => {
const result = await useCase.execute({
email: 'test@example.com',
password: 'weak',
displayName: 'John Smith',
});
expect(result.isErr()).toBe(true);
expect(result.unwrapErr().code).toBe('WEAK_PASSWORD');
});
it('returns error for invalid display name', async () => {
const result = await useCase.execute({
email: 'test@example.com',
password: 'Password123',
displayName: 'A', // Too short
});
expect(result.isErr()).toBe(true);
expect(result.unwrapErr().code).toBe('INVALID_DISPLAY_NAME');
});
});