user.service.spec.ts 2.0 KB

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