user.service.spec.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { Test, TestingModule } from '@nestjs/testing';
  2. import { CreateUserUseCase } from '../src/application/use-cases/create-user.use-case';
  3. import { IUserRepository } from '../src/application/interfaces/i-user.repository';
  4. import { IHasherService } from '../src/application/interfaces/i-hasher.service';
  5. import { UserRole } from '../src/domain/entities/user.entity';
  6. describe('CreateUserUseCase', () => {
  7. let useCase: CreateUserUseCase;
  8. let userRepository: IUserRepository;
  9. let hasherService: IHasherService;
  10. beforeEach(async () => {
  11. const module: TestingModule = await Test.createTestingModule({
  12. providers: [
  13. CreateUserUseCase,
  14. {
  15. provide: 'IUserRepository',
  16. useValue: {
  17. create: jest.fn(),
  18. findByEmail: jest.fn(),
  19. },
  20. },
  21. {
  22. provide: 'IHasherService',
  23. useValue: {
  24. hash: jest.fn(),
  25. },
  26. },
  27. ],
  28. }).compile();
  29. useCase = module.get<CreateUserUseCase>(CreateUserUseCase);
  30. userRepository = module.get<IUserRepository>('IUserRepository');
  31. hasherService = module.get<IHasherService>('IHasherService');
  32. });
  33. it('should be defined', () => {
  34. expect(useCase).toBeDefined();
  35. });
  36. it('should create a user successfully', async () => {
  37. const createUserDto = {
  38. email: 'test@test.com',
  39. password: 'password123',
  40. name: 'Test User',
  41. otherName: 'Other Name',
  42. address: 'Test Address',
  43. telephone: '1234567890',
  44. };
  45. const hashedPassword = 'hashedPassword123';
  46. const createdUser = { ...createUserDto, id: 1, password: hashedPassword, role: UserRole.USER };
  47. jest.spyOn(hasherService, 'hash').mockResolvedValue(hashedPassword);
  48. jest.spyOn(userRepository, 'create').mockResolvedValue(createdUser);
  49. const result = await useCase.execute(createUserDto);
  50. expect(result).toEqual(createdUser);
  51. expect(hasherService.hash).toHaveBeenCalledWith(createUserDto.password);
  52. expect(userRepository.create).toHaveBeenCalledWith({
  53. ...createUserDto,
  54. password: hashedPassword,
  55. });
  56. });
  57. });