diff --git a/src/admin/admin.controller.spec.ts b/src/admin/admin.controller.spec.ts index f08f68c7f73c75c86ce4acc90d0314d5f746fefa..fb64d7de7e1b9a848700232a44c69c56ee451bc2 100644 --- a/src/admin/admin.controller.spec.ts +++ b/src/admin/admin.controller.spec.ts @@ -9,6 +9,8 @@ import { StructuresServiceMock } from '../../test/mock/services/structures.mock. import { UsersServiceMock } from '../../test/mock/services/user.mock.service'; import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard'; import { ConfigurationModule } from '../configuration/configuration.module'; +import { EspaceCoopCNFS } from '../espaceCoop/schemas/espaceCoopCNFS.schema'; +import { EspaceCoopService } from '../espaceCoop/services/espaceCoop.service'; import { MailerService } from '../mailer/mailer.service'; import { NewsletterSubscription } from '../newsletter/newsletter-subscription.schema'; import { NewsletterService } from '../newsletter/newsletter.service'; @@ -25,11 +27,9 @@ import { UsersService } from '../users/services/users.service'; import { AdminController } from './admin.controller'; import { AdminService } from './admin.service'; import { PendingStructureDto } from './dto/pending-structure.dto'; -import { EspaceCoopService } from '../espaceCoop/services/espaceCoop.service'; -import { EspaceCoopCNFS } from '../espaceCoop/schemas/espaceCoopCNFS.schema'; describe('AdminController', () => { - let controller: AdminController; + let adminController: AdminController; let userService: UsersService; const mockEmployerSearchService = { @@ -132,28 +132,28 @@ describe('AdminController', () => { .useValue(mockRoleGuard) .compile(); - controller = module.get<AdminController>(AdminController); + adminController = module.get<AdminController>(AdminController); userService = module.get<UsersService>(UsersService); }); it('should be defined', () => { - expect(controller).toBeDefined(); + expect(adminController).toBeDefined(); }); it('should get pending attachments', async () => { - expect((await controller.getPendingAttachments()).length).toBe(2); - expect(Object.keys((await controller.getPendingAttachments())[0]).length).toBe(5); + expect((await adminController.getPendingAttachments()).length).toBe(2); + expect(Object.keys((await adminController.getPendingAttachments())[0]).length).toBe(5); }); describe('Pending structures validation', () => { it('should validate pending structure', async () => { - expect((await controller.validatePendingStructure(pendingStructureTest)).length).toBe(2); - expect(Object.keys((await controller.validatePendingStructure(pendingStructureTest))[0]).length).toBe(5); + expect((await adminController.validatePendingStructure(pendingStructureTest)).length).toBe(2); + expect(Object.keys((await adminController.validatePendingStructure(pendingStructureTest))[0]).length).toBe(5); }); it('should get structure does not exist', async () => { try { - await controller.validatePendingStructure(pendingStructureTest); + await adminController.validatePendingStructure(pendingStructureTest); } catch (e) { expect(e.message).toBe('Structure does not exist'); expect(e.status).toBe(404); @@ -163,13 +163,13 @@ describe('AdminController', () => { describe('Pending structures cancel', () => { it('should refuse pending structure', async () => { - expect((await controller.refusePendingStructure(pendingStructureTest)).length).toBe(2); - expect(Object.keys((await controller.refusePendingStructure(pendingStructureTest))[0]).length).toBe(5); + expect((await adminController.refusePendingStructure(pendingStructureTest)).length).toBe(2); + expect(Object.keys((await adminController.refusePendingStructure(pendingStructureTest))[0]).length).toBe(5); }); it('should get structure does not exist', async () => { try { - await controller.refusePendingStructure(pendingStructureTest); + await adminController.refusePendingStructure(pendingStructureTest); } catch (e) { expect(e.message).toBe('Structure does not exist'); expect(e.status).toBe(404); @@ -179,11 +179,11 @@ describe('AdminController', () => { describe('Delete user', () => { it('should delete user', async () => { - expect((await controller.deleteUser({ id: 'tsfsf6296' })).email).toBe('pauline.dupont@mii.com'); + expect((await adminController.deleteUser({ id: 'tsfsf6296' })).email).toBe('pauline.dupont@mii.com'); }); it('should return unexisting user', async () => { try { - await controller.deleteUser({ id: 'userdoesnotexist' }); + await adminController.deleteUser({ id: 'userdoesnotexist' }); } catch (e) { expect(e.message).toBe('Invalid user id'); expect(e.status).toBe(400); @@ -201,7 +201,7 @@ describe('AdminController', () => { validated: true, }; mockEmployerService.findOne.mockResolvedValueOnce(mockEmployer); - const reply = await controller.setUserEmployer({ + const reply = await adminController.setUserEmployer({ userId: mockUserId, employerId: String(mockEmployer._id), }); @@ -220,7 +220,7 @@ describe('AdminController', () => { }; mockEmployerService.findOne.mockResolvedValueOnce(null); try { - await controller.setUserEmployer({ + await adminController.setUserEmployer({ userId: mockUserId, employerId: String(mockEmployer._id), }); @@ -242,7 +242,7 @@ describe('AdminController', () => { }; mockEmployerService.findOne.mockResolvedValueOnce(mockEmployer); try { - await controller.setUserEmployer({ + await adminController.setUserEmployer({ userId: mockUserId, employerId: String(mockEmployer._id), }); @@ -265,7 +265,7 @@ describe('AdminController', () => { validated: true, }; mockJobService.findOne.mockResolvedValueOnce(mockJob); - const reply = await controller.setUserJob({ + const reply = await adminController.setUserJob({ userId: mockUserId, jobId: String(mockJob._id), }); @@ -284,7 +284,7 @@ describe('AdminController', () => { }; mockJobService.findOne.mockResolvedValueOnce(null); try { - await controller.setUserJob({ + await adminController.setUserJob({ userId: mockUserId, jobId: String(mockJob._id), }); @@ -306,7 +306,7 @@ describe('AdminController', () => { }; mockJobService.findOne.mockResolvedValueOnce(mockJob); try { - await controller.setUserJob({ + await adminController.setUserJob({ userId: mockUserId, jobId: String(mockJob._id), }); @@ -321,28 +321,28 @@ describe('AdminController', () => { describe('Search user', () => { it('should return all users, empty string', async () => { - expect((await controller.searchUsers({ searchString: '' })).length).toBe(2); + expect((await adminController.searchUsers({ searchString: '' })).length).toBe(2); }); it('should return all users, null input', async () => { - expect((await controller.searchUsers({ searchString: null })).length).toBe(2); + expect((await adminController.searchUsers({ searchString: null })).length).toBe(2); }); it('should one user', async () => { - expect((await controller.searchUsers({ searchString: 'a@a.com' })).length).toBe(1); - expect((await controller.searchUsers({ searchString: 'a@a.com' }))[0].email).toBe('a@a.com'); + expect((await adminController.searchUsers({ searchString: 'a@a.com' })).length).toBe(1); + expect((await adminController.searchUsers({ searchString: 'a@a.com' }))[0].email).toBe('a@a.com'); }); it('should no user', async () => { - expect((await controller.searchUsers({ searchString: 'dfqfqsfqfqfa@a.com' })).length).toBe(0); + expect((await adminController.searchUsers({ searchString: 'dfqfqsfqfqfa@a.com' })).length).toBe(0); }); }); describe('Search delete a user subscription', () => { it('should return a deleted object', async () => { - expect((await controller.unsubscribeUserFromNewsletter('a@a.com')).email).toBe('a@a.com'); - expect(Object.keys(await controller.unsubscribeUserFromNewsletter('a@a.com')).length).toBe(4); + expect((await adminController.unsubscribeUserFromNewsletter('a@a.com')).email).toBe('a@a.com'); + expect(Object.keys(await adminController.unsubscribeUserFromNewsletter('a@a.com')).length).toBe(4); }); it('should throw an error', async () => { try { - await controller.unsubscribeUserFromNewsletter('test@test.com'); + await adminController.unsubscribeUserFromNewsletter('test@test.com'); } catch (e) { expect(e.message).toBe('Invalid email'); expect(e.status).toBe(401); @@ -351,27 +351,27 @@ describe('AdminController', () => { }); it('should get pending structure list for admin', async () => { - expect((await controller.getAdminStructuresList()).inClaim.length).toBe(2); - expect((await controller.getAdminStructuresList()).toClaim.length).toEqual(2); - expect((await controller.getAdminStructuresList()).claimed.length).toEqual(2); - expect((await controller.getAdminStructuresList()).incomplete.length).toEqual(2); + expect((await adminController.getAdminStructuresList()).inClaim.length).toBe(2); + expect((await adminController.getAdminStructuresList()).toClaim.length).toEqual(2); + expect((await adminController.getAdminStructuresList()).claimed.length).toEqual(2); + expect((await adminController.getAdminStructuresList()).incomplete.length).toEqual(2); }); it('should find attached users', async () => { - expect((await controller.findAttachedUsers()).length).toBe(0); + expect((await adminController.findAttachedUsers()).length).toBe(0); }); it('should find unattached users', async () => { - expect((await controller.findUnattachedUsers()).length).toBe(0); + expect((await adminController.findUnattachedUsers()).length).toBe(0); }); it('should find unverified users', async () => { - expect((await controller.findUnVerifiedUsers()).length).toBe(0); + expect((await adminController.findUnVerifiedUsers()).length).toBe(0); }); describe('should test getDeletedStructures()', () => { it('should find getDeletedStructures', async () => { - expect((await controller.getDeletedStructures()).length).toBeGreaterThan(0); + expect((await adminController.getDeletedStructures()).length).toBeGreaterThan(0); }); }); }); diff --git a/src/admin/admin.service.spec.ts b/src/admin/admin.service.spec.ts index 5e5e153df03a8437915bb59ff2861c9366e40f02..99d58a8c0c44ae7f6ce9907229234ef7a590b592 100644 --- a/src/admin/admin.service.spec.ts +++ b/src/admin/admin.service.spec.ts @@ -2,17 +2,17 @@ import { Test, TestingModule } from '@nestjs/testing'; import { AdminService } from './admin.service'; describe('AdminService', () => { - let service: AdminService; + let adminService: AdminService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [AdminService], }).compile(); - service = module.get<AdminService>(AdminService); + adminService = module.get<AdminService>(AdminService); }); it('should be defined', () => { - expect(service).toBeDefined(); + expect(adminService).toBeDefined(); }); }); diff --git a/src/appointment/appointment.controller.spec.ts b/src/appointment/appointment.controller.spec.ts index 805bfa31a616e8e4c19fd0fa7f91de202df29745..9b8d25cfae142cac4b743e54ca2332b40a960d3a 100644 --- a/src/appointment/appointment.controller.spec.ts +++ b/src/appointment/appointment.controller.spec.ts @@ -6,7 +6,7 @@ import { Appointment } from './appointment.schema'; import { AppointmentService } from './appointment.service'; describe('UserRegistryController', () => { - let controller: AppointmentController; + let appoinmentController: AppointmentController; const appointmentServiceMock = { findAll: jest.fn(), @@ -29,24 +29,24 @@ describe('UserRegistryController', () => { controllers: [AppointmentController], }).compile(); - controller = module.get<AppointmentController>(AppointmentController); + appoinmentController = module.get<AppointmentController>(AppointmentController); }); it('should be defined', () => { - expect(controller).toBeDefined(); + expect(appoinmentController).toBeDefined(); }); describe('findAll', () => { it('should findAll entries', async () => { appointmentServiceMock.findAll.mockResolvedValue(appointmentMockData); - const reply = await controller.findAll(); + const reply = await appoinmentController.findAll(); expect(reply).toStrictEqual(appointmentMockData); }); }); describe('createAppointment', () => { it('should create a new entry', async () => { appointmentServiceMock.create.mockResolvedValue(singleAppointmentMock); - const reply = await controller.createAppointment(singleAppointmentMock); + const reply = await appoinmentController.createAppointment(singleAppointmentMock); expect(reply).toStrictEqual(singleAppointmentMock); }); }); diff --git a/src/appointment/appointment.service.spec.ts b/src/appointment/appointment.service.spec.ts index 57554ba2bdd9953a5588a9c64dc6ac9ac1a2bd0e..becd2e4f0db3b7175fa50c9834ffdf6ce576c95c 100644 --- a/src/appointment/appointment.service.spec.ts +++ b/src/appointment/appointment.service.spec.ts @@ -1,19 +1,20 @@ +import { HttpModule } from '@nestjs/axios'; import { getModelToken } from '@nestjs/mongoose'; import { Test, TestingModule } from '@nestjs/testing'; -import { AppointmentService } from './appointment.service'; +import * as ejs from 'ejs'; import { appointmentMockData } from '../../test/mock/data/appointment.mock.data'; -import { MailerService } from '../mailer/mailer.service'; +import { StructuresServiceMock } from '../../test/mock/services/structures.mock.service'; +import { UsersServiceMock } from '../../test/mock/services/user.mock.service'; import { MailerModule } from '../mailer/mailer.module'; -import { HttpModule } from '@nestjs/axios'; -import { UsersService } from '../users/services/users.service'; +import { MailerService } from '../mailer/mailer.service'; import { StructuresService } from '../structures/services/structures.service'; -import { UsersServiceMock } from '../../test/mock/services/user.mock.service'; -import { StructuresServiceMock } from '../../test/mock/services/structures.mock.service'; -import * as ejs from 'ejs'; +import { UsersService } from '../users/services/users.service'; +import { AppointmentService } from './appointment.service'; jest.mock('ejs'); describe('userRegistryService', () => { - let service: AppointmentService; + let appointmentService: AppointmentService; + const mockAppointmentModel = { find: jest.fn(() => mockAppointmentModel), create: jest.fn(() => mockAppointmentModel), @@ -58,17 +59,17 @@ describe('userRegistryService', () => { }, ], }).compile(); - service = module.get<AppointmentService>(AppointmentService); + appointmentService = module.get<AppointmentService>(AppointmentService); }); it('should be defined', () => { - expect(service).toBeDefined(); + expect(appointmentService).toBeDefined(); }); describe('findAll', () => { it('should findAll entries', async () => { mockAppointmentModel.exec.mockResolvedValueOnce(appointmentMockData); - expect(await service.findAll()).toBe(appointmentMockData); + expect(await appointmentService.findAll()).toBe(appointmentMockData); }); }); describe('create', () => { @@ -86,7 +87,7 @@ describe('userRegistryService', () => { mockMailService.loadJsonConfig.mockReturnValueOnce({ subject: 'Teste Mail' }); ejsSpy.mockResolvedValueOnce('coucou'); mockAppointmentModel.create.mockResolvedValueOnce(res); - expect(await service.create(res)).toStrictEqual(res); + expect(await appointmentService.create(res)).toStrictEqual(res); expect(mailerSpy).toHaveBeenCalledTimes(1); }); }); diff --git a/src/auth/auth.controller.spec.ts b/src/auth/auth.controller.spec.ts index c69a22cedef0473b462d16ad13b9ea84f61b90a3..3feefc99c2d1448c80bde58e026a0be4bff84858 100644 --- a/src/auth/auth.controller.spec.ts +++ b/src/auth/auth.controller.spec.ts @@ -1,26 +1,26 @@ +import { HttpService } from '@nestjs/axios'; import { JwtModule } from '@nestjs/jwt'; import { getModelToken } from '@nestjs/mongoose'; import { PassportModule } from '@nestjs/passport'; import { Test, TestingModule } from '@nestjs/testing'; import { AuthServiceMock } from '../../test/mock/services/auth.mock.service'; +import { StructuresServiceMock } from '../../test/mock/services/structures.mock.service'; +import { CategoriesService } from '../categories/services/categories.service'; import { ConfigurationModule } from '../configuration/configuration.module'; import { MailerModule } from '../mailer/mailer.module'; +import { StructuresSearchService } from '../structures/services/structures-search.service'; +import { StructuresService } from '../structures/services/structures.service'; +import { Job } from '../users/schemas/job.schema'; import { User } from '../users/schemas/user.schema'; +import { JobsService } from '../users/services/jobs.service'; import { UserRegistrySearchService } from '../users/services/userRegistry-search.service'; import { UsersService } from '../users/services/users.service'; import { AuthController } from './auth.controller'; import { AuthService } from './auth.service'; import { LoginDto } from './login-dto'; -import { JobsService } from '../users/services/jobs.service'; -import { Job } from '../users/schemas/job.schema'; -import { StructuresService } from '../structures/services/structures.service'; -import { HttpService } from '@nestjs/axios'; -import { StructuresSearchService } from '../structures/services/structures-search.service'; -import { CategoriesService } from '../categories/services/categories.service'; -import { StructuresServiceMock } from '../../test/mock/services/structures.mock.service'; describe('AuthController', () => { - let controller: AuthController; + let authController: AuthController; const httpServiceMock = { get: jest.fn(), @@ -83,16 +83,16 @@ describe('AuthController', () => { ], }).compile(); - controller = module.get<AuthController>(AuthController); + authController = module.get<AuthController>(AuthController); }); it('should be defined', () => { - expect(controller).toBeDefined(); + expect(authController).toBeDefined(); }); it('should login valid user', async () => { const loginCredentials: LoginDto = { email: 'paula.dubois@mii.com', password: process.env.USER_PWD }; - const result = await controller.login(loginCredentials); + const result = await authController.login(loginCredentials); expect(result).toStrictEqual({ _id: 'tsfsf6296', email: 'pauline.dupont@mii.com', @@ -109,7 +109,7 @@ describe('AuthController', () => { it('should not login invalid user', async () => { const loginCredentials: LoginDto = { email: 'jacques.dupont@mii.com', password: process.env.USER_PWD }; try { - await controller.login(loginCredentials); + await authController.login(loginCredentials); } catch (e) { expect(e.response).toBe('Invalid credentials'); expect(e.message).toBe('Invalid credentials'); diff --git a/src/auth/auth.service.spec.ts b/src/auth/auth.service.spec.ts index 134ae6351a8f5b607495244ce72f0c1458c2b1b1..a8784080413008e5be0f0dd37be15f5281c0851d 100644 --- a/src/auth/auth.service.spec.ts +++ b/src/auth/auth.service.spec.ts @@ -10,7 +10,7 @@ import { AuthService } from './auth.service'; import { LoginDto } from './login-dto'; describe('AuthService', () => { - let service: AuthService; + let authService: AuthService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ @@ -28,11 +28,11 @@ describe('AuthService', () => { ], }).compile(); - service = module.get<AuthService>(AuthService); + authService = module.get<AuthService>(AuthService); }); it('should be defined', () => { - expect(service).toBeDefined(); + expect(authService).toBeDefined(); }); describe('validateUser', () => { @@ -47,12 +47,12 @@ describe('AuthService', () => { personalOffers: [], }; const loginDto: LoginDto = { email: 'jacques.dupont@mii.com', password: 'test1A!!' }; //NOSONAR - expect(await service.validateUser(loginDto)).toStrictEqual(result); + expect(await authService.validateUser(loginDto)).toStrictEqual(result); }); it('should not validateUser', async () => { const loginDto: LoginDto = { email: 'tom.dupont@mii.com', password: 'test1A!!!' }; //NOSONAR - expect(await service.validateUser(loginDto)).toBe(null); + expect(await authService.validateUser(loginDto)).toBe(null); }); }); @@ -71,7 +71,7 @@ describe('AuthService', () => { _createToken.mockImplementation(() => token); const loginDto: LoginDto = { email: 'pauline.dupont@mii.com', password: 'test1A!!' }; //NOSONAR - expect(await service.login(loginDto)).toStrictEqual({ + expect(await authService.login(loginDto)).toStrictEqual({ accessToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InBhdWxpbmUuZHVwb250QG1paS5jb20iLCJyb2xlIjowLCJpYXQiOjE2MjAwNDg5MDYsImV4cCI6MTYyMDEzNTMwNn0.jbLazQNJzU_X9Yp1S7XH1rYD5W7yyd1pdGebmkyTMB4', expiresAt: '2021-05-04T15:35:06.663+02:00', @@ -92,7 +92,7 @@ describe('AuthService', () => { const loginDto: LoginDto = { email: 'jacques.dupont@mii.com', password: 'test1A!!' }; //NOSONAR try { - await service.login(loginDto); + await authService.login(loginDto); } catch (e) { expect(e.response).toBe('Invalid credentials'); expect(e.message).toBe('Invalid credentials'); @@ -111,7 +111,7 @@ describe('AuthService', () => { const loginDto: LoginDto = { email: 'toto@mii.com', password: 'test1A!!' }; //NOSONAR try { - await service.login(loginDto); + await authService.login(loginDto); } catch (e) { expect(e.response).toBe('Invalid credentials'); expect(e.message).toBe('Invalid credentials'); @@ -130,7 +130,7 @@ describe('AuthService', () => { const loginDto: LoginDto = { email: 'jacques.dupont@mii.com', password: '1' }; //NOSONAR try { - await service.login(loginDto); + await authService.login(loginDto); } catch (e) { expect(e.response).toBe('Invalid credentials'); expect(e.message).toBe('Invalid credentials'); diff --git a/src/categories/controllers/categories.controller.spec.ts b/src/categories/controllers/categories.controller.spec.ts index b523580de9e5bbc1b4bc0b9722d1f97fa0fdea90..cc6d7e44f84c0011efae5c204dfe4e1d27068860 100644 --- a/src/categories/controllers/categories.controller.spec.ts +++ b/src/categories/controllers/categories.controller.spec.ts @@ -10,7 +10,7 @@ import { CategoriesService } from '../services/categories.service'; import { CategoriesController } from './categories.controller'; describe('CategoriesAccompagnementController', () => { - let controller: CategoriesController; + let categoriesController: CategoriesController; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ @@ -33,15 +33,15 @@ describe('CategoriesAccompagnementController', () => { .useValue(mockRoleGuard) .compile(); - controller = module.get<CategoriesController>(CategoriesController); + categoriesController = module.get<CategoriesController>(CategoriesController); }); it('should be defined', () => { - expect(controller).toBeDefined(); + expect(categoriesController).toBeDefined(); }); it('should find all accompagnements', async () => { - expect((await controller.findAll()).length).toBe(1); - expect((await controller.findAll())[0].modules.length).toBe(8); + expect((await categoriesController.findAll()).length).toBe(1); + expect((await categoriesController.findAll())[0].modules.length).toBe(8); }); }); diff --git a/src/categories/services/categories.service.spec.ts b/src/categories/services/categories.service.spec.ts index 125760f11ae8bc904623916b72cbaa18d758912c..d1e2362cf82d90aa06b3afecb8efe949d20d04f5 100644 --- a/src/categories/services/categories.service.spec.ts +++ b/src/categories/services/categories.service.spec.ts @@ -5,7 +5,7 @@ import { CreateCategories } from '../dto/create-categories.dto'; import { CategoriesService } from './categories.service'; describe('CategoriesService', () => { - let service: CategoriesService; + let categoriesService: CategoriesService; const mockCategoriesModel = { create: jest.fn(), @@ -27,11 +27,11 @@ describe('CategoriesService', () => { ], }).compile(); - service = module.get<CategoriesService>(CategoriesService); + categoriesService = module.get<CategoriesService>(CategoriesService); }); it('should be defined', () => { - expect(service).toBeDefined(); + expect(categoriesService).toBeDefined(); }); it('should findAll structures', async () => { @@ -41,7 +41,7 @@ describe('CategoriesService', () => { ]; mockCategoriesModel.find.mockReturnThis(); mockCategoriesModel.exec.mockResolvedValueOnce(data); - expect(await service.findAll()).toEqual(data); + expect(await categoriesService.findAll()).toEqual(data); }); it('should findOneComplete structures', async () => { const data: CreateCategories[] = [ @@ -50,6 +50,6 @@ describe('CategoriesService', () => { ]; mockCategoriesModel.findOne.mockReturnThis(); mockCategoriesModel.exec.mockResolvedValueOnce(data); - expect(await service.findOneComplete('categoryId')).toEqual(data); + expect(await categoriesService.findOneComplete('categoryId')).toEqual(data); }); }); diff --git a/src/configuration/configuration.service.spec.ts b/src/configuration/configuration.service.spec.ts index a5ddba0b94c2d6b95b5846ca549160d01bf42275..7c48290aa1a810155c7b5bb227b3f52a3fc45a62 100644 --- a/src/configuration/configuration.service.spec.ts +++ b/src/configuration/configuration.service.spec.ts @@ -2,7 +2,7 @@ import { Test, TestingModule } from '@nestjs/testing'; import { ConfigurationService } from './configuration.service'; describe('ConfigurationService', () => { - let service: ConfigurationService; + let configurationService: ConfigurationService; process.env.NODE_ENV = 'local'; @@ -12,7 +12,7 @@ describe('ConfigurationService', () => { providers: [ConfigurationService], }).compile(); - service = module.get<ConfigurationService>(ConfigurationService); + configurationService = module.get<ConfigurationService>(ConfigurationService); }); describe('initialisation', () => { @@ -28,12 +28,12 @@ describe('ConfigurationService', () => { }); it('should be defined', () => { - expect(service).toBeDefined(); + expect(configurationService).toBeDefined(); }); it('should init with dev conf', () => { process.env.NODE_ENV = 'dev'; - expect(service.config.host).toBe('resin-dev.grandlyon.com'); + expect(configurationService.config.host).toBe('resin-dev.grandlyon.com'); }); }); @@ -50,25 +50,25 @@ describe('ConfigurationService', () => { }); it('should be defined', () => { - expect(service).toBeDefined(); + expect(configurationService).toBeDefined(); }); it('should init with prod conf', () => { process.env.NODE_ENV = 'production'; - expect(service.config.host).toBe('resin.grandlyon.com'); + expect(configurationService.config.host).toBe('resin.grandlyon.com'); }); }); describe('validateUser', () => { it('should be local conf', () => { process.env.NODE_ENV = 'local'; - expect(service.isLocalConf()).toBe(true); + expect(configurationService.isLocalConf()).toBe(true); }); }); describe('get config', () => { it('should get config', () => { - const config = service.config; + const config = configurationService.config; expect(Object.keys(config).length).toBe(9); expect(Object.keys(config)).toEqual( expect.arrayContaining([ diff --git a/src/contact/contact.controller.spec.ts b/src/contact/contact.controller.spec.ts index 7123437dd460c44b0e7858d71fd497cc5a421ffd..beb188f7c5dba07baa84d6520b37abe82f8370ac 100644 --- a/src/contact/contact.controller.spec.ts +++ b/src/contact/contact.controller.spec.ts @@ -1,11 +1,11 @@ import { Test, TestingModule } from '@nestjs/testing'; +import { MailerModule } from '../mailer/mailer.module'; import { ContactController } from './contact.controller'; import { ContactService } from './contact.service'; -import { MailerModule } from '../mailer/mailer.module'; import { ContactMessage } from './schemas/contact-message.schema'; describe('ContactController', () => { - let controller: ContactController; + let contactController: ContactController; const contactServiceMock = { sendMessage: jest.fn(), @@ -23,16 +23,16 @@ describe('ContactController', () => { controllers: [ContactController], }).compile(); - controller = module.get<ContactController>(ContactController); + contactController = module.get<ContactController>(ContactController); }); it('should be defined', () => { - expect(controller).toBeDefined(); + expect(contactController).toBeDefined(); }); it('should call sendMessage', async () => { const spyer = jest.spyOn(contactServiceMock, 'sendMessage'); - await controller.sendContactMessage({ contactMessage: new ContactMessage() }); + await contactController.sendContactMessage({ contactMessage: new ContactMessage() }); expect(spyer).toBeCalledTimes(1); expect(spyer).toBeCalledWith(new ContactMessage()); }); diff --git a/src/contact/contact.service.spec.ts b/src/contact/contact.service.spec.ts index c8558d105cac8fae27b7745225072f52a064f36d..259986b32c21506e74e8d9bd73eb9a37d79330a4 100644 --- a/src/contact/contact.service.spec.ts +++ b/src/contact/contact.service.spec.ts @@ -9,7 +9,7 @@ import { ContactService } from './contact.service'; import { ContactMessage } from './schemas/contact-message.schema'; describe('ContactService', () => { - let service: ContactService; + let contactService: ContactService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ @@ -17,15 +17,15 @@ describe('ContactService', () => { providers: [ContactService, ConfigurationService, { provide: MailerService, useClass: MailerMockService }], }).compile(); - service = module.get<ContactService>(ContactService); + contactService = module.get<ContactService>(ContactService); }); it('should be defined', () => { - expect(service).toBeDefined(); + expect(contactService).toBeDefined(); }); it('should send message with status OK', async () => { - const res = (await service.sendMessage(new ContactMessage())) as { data: { status: unknown } }; + const res = (await contactService.sendMessage(new ContactMessage())) as { data: { status: unknown } }; expect(res.data.status).toBe(HttpStatus.OK); }); }); diff --git a/src/espaceCoop/services/espaceCoop.service.spec.ts b/src/espaceCoop/services/espaceCoop.service.spec.ts index 24ba0e96bc371982228579da4bb4d4d65f4fc742..cb11ebbef934baaabffe8275cb5ee8f9b879b896 100644 --- a/src/espaceCoop/services/espaceCoop.service.spec.ts +++ b/src/espaceCoop/services/espaceCoop.service.spec.ts @@ -1,16 +1,16 @@ import { HttpService } from '@nestjs/axios'; import { getModelToken } from '@nestjs/mongoose'; import { Test, TestingModule } from '@nestjs/testing'; -import { UsersService } from '../../users/services/users.service'; import { espaceCoopCNFSMockData, espaceCoopPermanencesMockData, } from '../../../test/mock/data/espaceCoopCNFS.mock.data'; -import { EspaceCoopService } from './espaceCoop.service'; import { usersMockData } from '../../../test/mock/data/users.mock.data'; +import { UsersService } from '../../users/services/users.service'; +import { EspaceCoopService } from './espaceCoop.service'; describe('EspaceCoopCNFSService', () => { - let service: EspaceCoopService; + let espaceCoopService: EspaceCoopService; const mockEspaceCoopCNFSModel = { create: jest.fn(), @@ -44,18 +44,18 @@ describe('EspaceCoopCNFSService', () => { ], }).compile(); - service = module.get<EspaceCoopService>(EspaceCoopService); + espaceCoopService = module.get<EspaceCoopService>(EspaceCoopService); }); it('should be defined', () => { - expect(service).toBeDefined(); + expect(espaceCoopService).toBeDefined(); }); describe('parsePermanences', () => { it('should parse correctly permanences', async () => { // Mock finding first cnfs in user database jest.spyOn(usersServiceMock, 'findOne').mockImplementationOnce(() => usersMockData[0]); - const result = await service.parsePermanences(espaceCoopPermanencesMockData); + const result = await espaceCoopService.parsePermanences(espaceCoopPermanencesMockData); expect(result).toStrictEqual(espaceCoopCNFSMockData); }); }); diff --git a/src/indicator/services/indicator.service.spec.ts b/src/indicator/services/indicator.service.spec.ts index b1bcf859d247816a335e414a2de4eb3a7b616b77..68b9e3480ad4b049e016bc55602314fb46e11f59 100644 --- a/src/indicator/services/indicator.service.spec.ts +++ b/src/indicator/services/indicator.service.spec.ts @@ -1,12 +1,12 @@ -import { Test, TestingModule } from '@nestjs/testing'; -import { IndicatorService } from './indicator.service'; import { getModelToken } from '@nestjs/mongoose'; -import { OrientationIndicator } from '../schemas/orientation-indicator.schema'; +import { Test, TestingModule } from '@nestjs/testing'; import { mockIndicator, mockIndicators } from '../../../test/mock/data/indicators/orientationIndicators.mock.data'; import { User } from '../../users/schemas/user.schema'; +import { OrientationIndicator } from '../schemas/orientation-indicator.schema'; +import { IndicatorService } from './indicator.service'; describe('IndicatorService', () => { - let service: IndicatorService; + let indicatorService: IndicatorService; let mockModel; beforeEach(async () => { @@ -29,18 +29,18 @@ describe('IndicatorService', () => { ], }).compile(); - service = module.get<IndicatorService>(IndicatorService); + indicatorService = module.get<IndicatorService>(IndicatorService); }); it('should be defined', () => { - expect(service).toBeDefined(); + expect(indicatorService).toBeDefined(); }); describe('createOrientation', () => { it('should create orientation indicator', async () => { mockModel.create.mockResolvedValue(mockIndicator); - const result = await service.createOrientation(mockIndicator); + const result = await indicatorService.createOrientation(mockIndicator); expect(result).toBe(mockIndicator); expect(mockModel.create).toHaveBeenCalledWith(mockIndicator); }); @@ -48,7 +48,7 @@ describe('IndicatorService', () => { it('should handle errors when creating orientation indicator', async () => { mockModel.create.mockRejectedValue(new Error('Some error')); - await expect(service.createOrientation(mockIndicator)).rejects.toThrow('Some error'); + await expect(indicatorService.createOrientation(mockIndicator)).rejects.toThrow('Some error'); }); }); @@ -56,7 +56,7 @@ describe('IndicatorService', () => { it('should retrieve all orientation indicators', async () => { mockModel.find.mockResolvedValue(mockIndicators); - const result = await service.getAllOrientation(); + const result = await indicatorService.getAllOrientation(); expect(result).toBe(mockIndicators); expect(mockModel.find).toHaveBeenCalledWith({}); }); @@ -64,7 +64,7 @@ describe('IndicatorService', () => { it('should handle errors when fetching all orientation indicators', async () => { mockModel.find.mockRejectedValue(new Error('Some fetching error')); - await expect(service.getAllOrientation()).rejects.toThrow('Some fetching error'); + await expect(indicatorService.getAllOrientation()).rejects.toThrow('Some fetching error'); }); }); }); diff --git a/src/mailer/mailer.service.spec.ts b/src/mailer/mailer.service.spec.ts index 1ebbe4a9cb4748423140b4816e8c209292a28460..c6798f184c998edc210040b14965b2bb01820f24 100644 --- a/src/mailer/mailer.service.spec.ts +++ b/src/mailer/mailer.service.spec.ts @@ -1,14 +1,14 @@ import { HttpModule, HttpService } from '@nestjs/axios'; import { Test, TestingModule } from '@nestjs/testing'; -import { of, throwError } from 'rxjs'; import { AxiosResponse } from 'axios'; -import { ConfigurationService } from '../configuration/configuration.service'; -import { MailerService } from './mailer.service'; import * as fs from 'fs'; import * as path from 'path'; +import { of, throwError } from 'rxjs'; +import { ConfigurationService } from '../configuration/configuration.service'; +import { MailerService } from './mailer.service'; describe('MailerService', () => { - let service: MailerService; + let mailerService: MailerService; let httpService: HttpService; beforeEach(async () => { @@ -17,12 +17,12 @@ describe('MailerService', () => { providers: [MailerService, ConfigurationService], }).compile(); - service = module.get<MailerService>(MailerService); + mailerService = module.get<MailerService>(MailerService); httpService = module.get<HttpService>(HttpService); }); it('should be defined', () => { - expect(service).toBeDefined(); + expect(mailerService).toBeDefined(); }); describe('email sending', () => { @@ -41,7 +41,7 @@ describe('MailerService', () => { config: {}, }; jest.spyOn(httpService, 'post').mockImplementationOnce(() => of(result)); - expect(await service.send('a@a.com', 'test', '<p>This is a test</p>')).toBe(result.data); + expect(await mailerService.send('a@a.com', 'test', '<p>This is a test</p>')).toBe(result.data); }); it('should not send email', async () => { @@ -60,7 +60,7 @@ describe('MailerService', () => { }; jest.spyOn(httpService, 'post').mockImplementationOnce(() => throwError(result)); try { - await service.send('a@a.com', 'test', '<p>This is a test</p>'); + await mailerService.send('a@a.com', 'test', '<p>This is a test</p>'); } catch (e) { expect(e.data.detail).toBe('There was a validation error'); expect(e.status).toBe(400); @@ -72,7 +72,7 @@ describe('MailerService', () => { it('should get template location', async () => { jest.spyOn(path, 'join').mockImplementationOnce(() => '/path/to/template'); jest.spyOn(fs, 'existsSync').mockImplementationOnce(() => true); - expect(service.getTemplateLocation('filename')).toBe('/path/to/template'); + expect(mailerService.getTemplateLocation('filename')).toBe('/path/to/template'); }); it('should not get template location', async () => { @@ -80,7 +80,7 @@ describe('MailerService', () => { jest.spyOn(path, 'join').mockImplementationOnce(() => '/path/to/filename'); jest.spyOn(fs, 'existsSync').mockImplementationOnce(() => false); try { - expect(service.getTemplateLocation(filename)).toBe('/path/to/template'); + expect(mailerService.getTemplateLocation(filename)).toBe('/path/to/template'); } catch (e) { expect(e.message).toBe(`Email template '${filename}' cannot be found in ./src/mailer/mail-templates`); } @@ -95,7 +95,7 @@ describe('MailerService', () => { const buf = Buffer.from(JSON.stringify(data), 'utf8'); jest.spyOn(fs, 'readFileSync').mockImplementationOnce(() => buf); jest.spyOn(JSON, 'parse').mockImplementationOnce(() => JSON.stringify(data)); - expect(service.loadJsonConfig('filename')).toStrictEqual(JSON.stringify(data)); + expect(mailerService.loadJsonConfig('filename')).toStrictEqual(JSON.stringify(data)); }); it('should not get template location', async () => { @@ -103,7 +103,7 @@ describe('MailerService', () => { jest.spyOn(path, 'join').mockImplementationOnce(() => '/path/to/filename'); jest.spyOn(fs, 'existsSync').mockImplementationOnce(() => false); try { - expect(service.loadJsonConfig(filename)).toBe('/path/to/template'); + expect(mailerService.loadJsonConfig(filename)).toBe('/path/to/template'); } catch (e) { expect(e.message).toBe( `Email json definition file '${filename}' cannot be found in ./src/mailer/mail-templates` @@ -114,7 +114,7 @@ describe('MailerService', () => { it('should add signature', async () => { const test = '<p>test email</p>'; - expect(service.addSignature(test)).toBe( + expect(mailerService.addSignature(test)).toBe( `<p>test email</p><br /><br /><p>L’équipe projet inclusion numérique.</p><p style="font-family:helvetica;font-size:24px;font-weight:bold;margin:0;">rés<span style="color:red;font-weight:400;">’in</span></p><br /><br /><p>Ce mail est automatique. Merci de ne pas y répondre.</p>` ); }); diff --git a/src/newsletter/newsletter.controller.spec.ts b/src/newsletter/newsletter.controller.spec.ts index a34e079996430365c3d7df51b8cb428cc9de789e..4f2e38748f2872166de6922732be5e5f74fa3182 100644 --- a/src/newsletter/newsletter.controller.spec.ts +++ b/src/newsletter/newsletter.controller.spec.ts @@ -6,7 +6,7 @@ import { NewsletterSubscription } from './newsletter-subscription.schema'; import { NewsletterController } from './newsletter.controller'; import { NewsletterService } from './newsletter.service'; describe('NewsletterController', () => { - let controller: NewsletterController; + let newsletterController: NewsletterController; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ @@ -21,28 +21,28 @@ describe('NewsletterController', () => { controllers: [NewsletterController], }).compile(); - controller = module.get<NewsletterController>(NewsletterController); + newsletterController = module.get<NewsletterController>(NewsletterController); }); it('should be defined', () => { - expect(controller).toBeDefined(); + expect(newsletterController).toBeDefined(); }); it('should subscribe user', async () => { const result = { email: 'email@test.com', mailchimpId: 'test' }; jest - .spyOn(controller, 'newsletterSubscribe') + .spyOn(newsletterController, 'newsletterSubscribe') .mockImplementation(async (): Promise<{ email; mailchimpId }> => result); const email = { email: 'email@test.com', mailchimpId: 'test' }; - expect(await controller.newsletterSubscribe(email)).toBe(result); + expect(await newsletterController.newsletterSubscribe(email)).toBe(result); }); it('should unsubscribe user', async () => { const result = { email: 'email@test.com', mailchimpId: 'test' }; jest - .spyOn(controller, 'newsletterUnsubscribe') + .spyOn(newsletterController, 'newsletterUnsubscribe') .mockImplementation(async (): Promise<{ email; mailchimpId }> => result); const email = { email: 'email@test.com', mailchimpId: 'test' }; - expect(await controller.newsletterUnsubscribe(email)).toBe(result); + expect(await newsletterController.newsletterUnsubscribe(email)).toBe(result); }); }); diff --git a/src/newsletter/newsletter.service.spec.ts b/src/newsletter/newsletter.service.spec.ts index 88b588dd5b158a12cffff59f86bf8a2c378545a1..ef809c4e01ab30ec6668edd2d602470260bc1779 100644 --- a/src/newsletter/newsletter.service.spec.ts +++ b/src/newsletter/newsletter.service.spec.ts @@ -10,7 +10,7 @@ const mailchimp = require('@mailchimp/mailchimp_marketing'); jest.mock('@mailchimp/mailchimp_marketing'); describe('NewsletterService', () => { const OLD_ENV = process.env; - let service: NewsletterService; + let newsletterService: NewsletterService; const mockNewsletterModel = { create: jest.fn(), @@ -34,7 +34,7 @@ describe('NewsletterService', () => { ], }).compile(); - service = module.get<NewsletterService>(NewsletterService); + newsletterService = module.get<NewsletterService>(NewsletterService); process.env = { ...OLD_ENV }; // Make a copy process.env.MC_LIST_ID = 'abcde'; @@ -47,7 +47,7 @@ describe('NewsletterService', () => { }); it('should be defined', () => { - expect(service).toBeDefined(); + expect(newsletterService).toBeDefined(); }); describe('newsletterSubscribe', () => { @@ -55,11 +55,11 @@ describe('NewsletterService', () => { const _doc = { _id: 'a1aaaaa1a1', email: 'test2@test.com' } as INewsletterSubscription; mailchimp.lists.setListMember.mockResolvedValueOnce({ email_address: 'test2@test.com' }); jest - .spyOn(service, 'findOne') + .spyOn(newsletterService, 'findOne') .mockImplementationOnce(async (): Promise<INewsletterSubscription | undefined> => _doc); mockNewsletterModel.create.mockResolvedValueOnce(_doc); - const subscription = await service.newsletterSubscribe('test2@test.com'); + const subscription = await newsletterService.newsletterSubscribe('test2@test.com'); expect(subscription).toEqual(_doc); }); it('it should add a subscription for email test2@test.com', async () => { @@ -67,12 +67,12 @@ describe('NewsletterService', () => { const _doc = { _id: 'a1aaaaa1a1', email: 'test2@test.com' }; mailchimp.lists.setListMember.mockResolvedValueOnce({ email_address: 'test2@test.com' }); jest - .spyOn(service, 'findOne') + .spyOn(newsletterService, 'findOne') .mockImplementationOnce(async (): Promise<INewsletterSubscription | undefined> => undefined) .mockImplementationOnce(async (): Promise<INewsletterSubscription | undefined> => result); mockNewsletterModel.create.mockResolvedValueOnce(_doc); - const subscription = await service.newsletterSubscribe('test2@test.com'); + const subscription = await newsletterService.newsletterSubscribe('test2@test.com'); expect(subscription).toEqual(_doc); }); it('it should return error if mailchimp 400 issue', async () => { @@ -80,13 +80,13 @@ describe('NewsletterService', () => { const _doc = { _id: 'a1aaaaa1a1', email: 'test2@test.com' }; mailchimp.lists.setListMember.mockRejectedValueOnce({ status: 400 }); jest - .spyOn(service, 'findOne') + .spyOn(newsletterService, 'findOne') .mockImplementationOnce(async (): Promise<INewsletterSubscription | undefined> => undefined) .mockImplementationOnce(async (): Promise<INewsletterSubscription | undefined> => result); mockNewsletterModel.create.mockResolvedValueOnce(_doc); try { - await service.newsletterSubscribe('test2@test.com'); + await newsletterService.newsletterSubscribe('test2@test.com'); expect(true).toBe(false); } catch (e) { expect(e.message).toBe('Subscribe error'); @@ -98,13 +98,13 @@ describe('NewsletterService', () => { const _doc = { _id: 'a1aaaaa1a1', email: 'test2@test.com' }; mailchimp.lists.setListMember.mockRejectedValueOnce({ status: 500 }); jest - .spyOn(service, 'findOne') + .spyOn(newsletterService, 'findOne') .mockImplementationOnce(async (): Promise<INewsletterSubscription | undefined> => undefined) .mockImplementationOnce(async (): Promise<INewsletterSubscription | undefined> => result); mockNewsletterModel.create.mockResolvedValueOnce(_doc); try { - await service.newsletterSubscribe('test2@test.com'); + await newsletterService.newsletterSubscribe('test2@test.com'); expect(true).toBe(false); } catch (e) { expect(e.message).toBe('Subscribe error'); @@ -118,7 +118,7 @@ describe('NewsletterService', () => { mockNewsletterModel.findOne.mockReturnThis(); mockNewsletterModel.exec.mockResolvedValueOnce(undefined); try { - await service.newsletterUnsubscribe('test@test.com'); + await newsletterService.newsletterUnsubscribe('test@test.com'); // Fail test if above expression doesn't throw anything. expect(true).toBe(false); } catch (e) { @@ -135,10 +135,10 @@ describe('NewsletterService', () => { deleteOne: async () => _doc, } as INewsletterSubscription; jest - .spyOn(service, 'findOne') + .spyOn(newsletterService, 'findOne') .mockImplementationOnce(async (): Promise<INewsletterSubscription | undefined> => result); - const subscription = await service.newsletterUnsubscribe('test2@test.com'); + const subscription = await newsletterService.newsletterUnsubscribe('test2@test.com'); expect(subscription).toEqual(_doc); }); }); @@ -147,14 +147,14 @@ describe('NewsletterService', () => { it('it should not find a subscription with email test@test.com', async () => { mockNewsletterModel.findOne.mockReturnThis(); mockNewsletterModel.exec.mockResolvedValueOnce(undefined); - const findOneEmail = await service.findOne('test@test.com'); + const findOneEmail = await newsletterService.findOne('test@test.com'); expect(findOneEmail).toEqual(undefined); }); it('it should find a subscription with email test2@test.com', async () => { const _doc = { _id: 'a1aaaaa1a1', email: 'test2@test.com' } as INewsletterSubscription; mockNewsletterModel.findOne.mockReturnThis(); mockNewsletterModel.exec.mockResolvedValueOnce(_doc); - const findOneEmail = await service.findOne('test2@test.com'); + const findOneEmail = await newsletterService.findOne('test2@test.com'); expect(findOneEmail).toEqual(_doc); }); }); @@ -163,7 +163,7 @@ describe('NewsletterService', () => { const _docs = [{ _id: 'a1aaaaa1a1', email: 'test2@test.com' } as INewsletterSubscription]; mockNewsletterModel.find.mockReturnThis(); mockNewsletterModel.exec.mockResolvedValueOnce(_docs); - const findOneEmail = await service.findAll(); + const findOneEmail = await newsletterService.findAll(); expect(findOneEmail).toEqual(_docs); }); }); @@ -179,7 +179,7 @@ describe('NewsletterService', () => { const result = { email: 'test2@test.com' } as INewsletterSubscription; const spyer = jest.spyOn(mockNewsletterModel, 'findOne'); mockNewsletterModel.findOne.mockResolvedValueOnce(result).mockResolvedValueOnce(null); - service.updateNewsletterSubscription(); + newsletterService.updateNewsletterSubscription(); expect(spyer).toBeCalledTimes(3); // expect(spyerDelete).toBeCalledTimes(1); }); diff --git a/src/online-mediation/onlineMediation.controller.spec.ts b/src/online-mediation/onlineMediation.controller.spec.ts index 12da2f398fb7c8bfbfdee1abacb8bc4fa217b730..ed01cbd4e0f2d16ae1826882c2069ec041adc124 100644 --- a/src/online-mediation/onlineMediation.controller.spec.ts +++ b/src/online-mediation/onlineMediation.controller.spec.ts @@ -6,7 +6,7 @@ import { OnlineMediation } from './onlineMediation.schema'; import { OnlineMediationService } from './onlineMediation.service'; describe('UserRegistryController', () => { - let controller: OnlineMediationController; + let onlineMediationController: OnlineMediationController; const onlineMediationServiceMock = { getAll: jest.fn(), @@ -29,24 +29,24 @@ describe('UserRegistryController', () => { controllers: [OnlineMediationController], }).compile(); - controller = module.get<OnlineMediationController>(OnlineMediationController); + onlineMediationController = module.get<OnlineMediationController>(OnlineMediationController); }); it('should be defined', () => { - expect(controller).toBeDefined(); + expect(onlineMediationController).toBeDefined(); }); describe('findAll', () => { it('should findAll entries', async () => { onlineMediationServiceMock.getAll.mockResolvedValue(onlineMediationMockData); - const reply = await controller.findAll(); + const reply = await onlineMediationController.findAll(); expect(reply).toStrictEqual(onlineMediationMockData); }); }); describe('createOnlineMediation', () => { it('should create a new entry', async () => { onlineMediationServiceMock.create.mockResolvedValue(singleOnlineMediationMock); - const reply = await controller.createOnlineMediation(singleOnlineMediationMock); + const reply = await onlineMediationController.createOnlineMediation(singleOnlineMediationMock); expect(reply).toStrictEqual(singleOnlineMediationMock); }); }); diff --git a/src/online-mediation/onlineMediation.service.spec.ts b/src/online-mediation/onlineMediation.service.spec.ts index d1a530a8266564237375c6b4e22b75c5865d28f7..cb0deafa2d03a12bb46b2d20b8c66a5f33720b29 100644 --- a/src/online-mediation/onlineMediation.service.spec.ts +++ b/src/online-mediation/onlineMediation.service.spec.ts @@ -1,16 +1,16 @@ +import { HttpModule } from '@nestjs/axios'; import { getModelToken } from '@nestjs/mongoose'; import { Test, TestingModule } from '@nestjs/testing'; -import { OnlineMediationService } from './onlineMediation.service'; +import * as ejs from 'ejs'; import { onlineMediationMockData } from '../../test/mock/data/onlineMediation.mock.data'; -import { MailerService } from '../mailer/mailer.service'; import { ConfigurationService } from '../configuration/configuration.service'; import { MailerModule } from '../mailer/mailer.module'; -import { HttpModule } from '@nestjs/axios'; -import * as ejs from 'ejs'; +import { MailerService } from '../mailer/mailer.service'; +import { OnlineMediationService } from './onlineMediation.service'; jest.mock('ejs'); describe('userRegistryService', () => { - let service: OnlineMediationService; + let onlineMediationService: OnlineMediationService; const mockOnlineMediationModel = { find: jest.fn(() => mockOnlineMediationModel), create: jest.fn(() => mockOnlineMediationModel), @@ -51,17 +51,17 @@ describe('userRegistryService', () => { }, ], }).compile(); - service = module.get<OnlineMediationService>(OnlineMediationService); + onlineMediationService = module.get<OnlineMediationService>(OnlineMediationService); }); it('should be defined', () => { - expect(service).toBeDefined(); + expect(onlineMediationService).toBeDefined(); }); describe('findAll', () => { it('should findAll entries', async () => { mockOnlineMediationModel.exec.mockResolvedValueOnce(onlineMediationMockData); - expect(await service.getAll()).toBe(onlineMediationMockData); + expect(await onlineMediationService.getAll()).toBe(onlineMediationMockData); }); }); describe('create', () => { @@ -76,7 +76,7 @@ describe('userRegistryService', () => { preferredLanguage: 'Français', }; mockOnlineMediationModel.create.mockResolvedValueOnce(res); - expect(await service.create(res)).toStrictEqual(res); + expect(await onlineMediationService.create(res)).toStrictEqual(res); }); }); describe('sendMailAndResetDb', () => { @@ -90,7 +90,7 @@ describe('userRegistryService', () => { mockOnlineMediationModel.exec.mockResolvedValueOnce(onlineMediationMockData.length); mockMailService.loadJsonConfig.mockReturnValueOnce({ subject: 'Teste Mail' }); ejsSpy.mockResolvedValueOnce('coucou'); - const response = await service.sendMailAndResetDb(); + const response = await onlineMediationService.sendMailAndResetDb(); expect(mailerSpy).toHaveBeenCalledTimes(1); expect(response).toBe(onlineMediationMockData.length); }); @@ -99,7 +99,7 @@ describe('userRegistryService', () => { mockOnlineMediationModel.exec.mockResolvedValueOnce(onlineMediationMockData); mockOnlineMediationModel.deleteMany.mockReturnThis(); mockOnlineMediationModel.exec.mockResolvedValueOnce(onlineMediationMockData.length); - const response = await service.sendMailAndResetDb(); + const response = await onlineMediationService.sendMailAndResetDb(); expect(mailerSpy).toHaveBeenCalledTimes(0); expect(response).toBe(onlineMediationMockData.length); }); diff --git a/src/pages/pages.controller.spec.ts b/src/pages/pages.controller.spec.ts index 3588405e54ce64b00e919bbbbf2c1f7c055a2663..daa3523a230a3300d2b63c8331d7166a6b8136d5 100644 --- a/src/pages/pages.controller.spec.ts +++ b/src/pages/pages.controller.spec.ts @@ -1,12 +1,12 @@ import { HttpModule, HttpService } from '@nestjs/axios'; import { Test, TestingModule } from '@nestjs/testing'; +import { AxiosResponse } from 'axios'; import { of } from 'rxjs'; import { ConfigurationModule } from '../configuration/configuration.module'; import { PagesController } from './pages.controller'; -import { AxiosResponse } from 'axios'; describe('PagesController', () => { - let controller: PagesController; + let pagesController: PagesController; const httpServiceMock = { get: jest.fn(), @@ -23,11 +23,11 @@ describe('PagesController', () => { controllers: [PagesController], }).compile(); - controller = module.get<PagesController>(PagesController); + pagesController = module.get<PagesController>(PagesController); }); it('should be defined', () => { - expect(controller).toBeDefined(); + expect(pagesController).toBeDefined(); }); describe('getPagebySlug', () => { @@ -84,7 +84,7 @@ describe('PagesController', () => { config: {}, }; httpServiceMock.get.mockImplementationOnce(() => of(axiosResult)); - const result = await (await controller.getPagebySlug('hello')).toPromise(); + const result = await (await pagesController.getPagebySlug('hello')).toPromise(); expect(result.pages).toStrictEqual(data); }); }); diff --git a/src/parameters/parameters.controller.spec.ts b/src/parameters/parameters.controller.spec.ts index b78180d3a3a7150a7388a919eca13d330354cbcb..8cad9081044f7ce6b6ec2a7e9f2562fb9922647b 100644 --- a/src/parameters/parameters.controller.spec.ts +++ b/src/parameters/parameters.controller.spec.ts @@ -5,7 +5,7 @@ import { ParametersService } from './parameters.service'; import { Parameters } from './schemas/parameters.schema'; describe('ParametersController', () => { - let controller: ParametersController; + let parametersController: ParametersController; const parametersServiceMock = { getParameters: jest.fn(), @@ -27,16 +27,16 @@ describe('ParametersController', () => { controllers: [ParametersController], }).compile(); - controller = module.get<ParametersController>(ParametersController); + parametersController = module.get<ParametersController>(ParametersController); }); it('should be defined', async () => { - expect(controller).toBeDefined(); + expect(parametersController).toBeDefined(); }); it('should call getParameters', async () => { const spyer = jest.spyOn(parametersServiceMock, 'getParameters'); - await controller.getParameters(); + await parametersController.getParameters(); expect(spyer).toBeCalledTimes(1); }); @@ -44,13 +44,13 @@ describe('ParametersController', () => { const spyer = jest.spyOn(parametersServiceMock, 'setParameterLockdownInfoDisplay'); afterEach(() => spyer.mockClear()); it('should call setParameterLockdownInfoDisplay(false) ', async () => { - await controller.setParameterLockdownInfoDisplay({ lockdownInfoDisplay: false }); + await parametersController.setParameterLockdownInfoDisplay({ lockdownInfoDisplay: false }); expect(spyer).toBeCalledTimes(1); expect(spyer).toBeCalledWith(false); }); it('should call setParameterLockdownInfoDisplay(true)', async () => { - await controller.setParameterLockdownInfoDisplay({ lockdownInfoDisplay: true }); + await parametersController.setParameterLockdownInfoDisplay({ lockdownInfoDisplay: true }); expect(spyer).toBeCalledTimes(1); expect(spyer).toBeCalledWith(true); }); diff --git a/src/parameters/parameters.service.spec.ts b/src/parameters/parameters.service.spec.ts index aba665562985592bcc1560c89a00e9d647d7c7c5..3b0f1375445455690c9d834c20cc9cc0ac1dd5ef 100644 --- a/src/parameters/parameters.service.spec.ts +++ b/src/parameters/parameters.service.spec.ts @@ -5,7 +5,7 @@ import { ParametersService } from './parameters.service'; import { Parameters } from './schemas/parameters.schema'; describe('ParametersService', () => { - let service: ParametersService; + let parametersService: ParametersService; const parametersModelMock = { findOne: jest.fn(), @@ -23,14 +23,14 @@ describe('ParametersService', () => { ], }).compile(); - service = module.get<ParametersService>(ParametersService); + parametersService = module.get<ParametersService>(ParametersService); }); afterEach(() => { jest.clearAllMocks(); }); it('should be defined', () => { - expect(service).toBeDefined(); + expect(parametersService).toBeDefined(); }); describe('getParameters', () => { @@ -39,7 +39,7 @@ describe('ParametersService', () => { parametersModelMock.findOne.mockReturnThis(); parametersModelMock.exec.mockResolvedValueOnce({ lockdownInfoDisplay: false }); - const result = await service.getParameters(); + const result = await parametersService.getParameters(); expect(spyer).toBeCalledTimes(1); expect(result).toEqual({ lockdownInfoDisplay: false }); }); @@ -50,7 +50,7 @@ describe('ParametersService', () => { parametersModelMock.exec.mockResolvedValueOnce(null); try { - await service.getParameters(); + await parametersService.getParameters(); expect(true).toBe(false); } catch (error) { expect(error.message).toBe('Parameters not found'); @@ -66,7 +66,7 @@ describe('ParametersService', () => { parametersModelMock.findOne.mockReturnThis(); parametersModelMock.exec.mockResolvedValueOnce({ lockdownInfoDisplay: false, save: jest.fn() }); - const result = await service.setParameterLockdownInfoDisplay(true); + const result = await parametersService.setParameterLockdownInfoDisplay(true); expect(spyer).toBeCalledTimes(1); expect(result.lockdownInfoDisplay).toEqual(true); }); @@ -77,7 +77,7 @@ describe('ParametersService', () => { parametersModelMock.exec.mockResolvedValueOnce(null); try { - await service.setParameterLockdownInfoDisplay(true); + await parametersService.setParameterLockdownInfoDisplay(true); expect(true).toBe(false); } catch (error) { expect(error.message).toBe('Parameters not found'); diff --git a/src/personal-offers/personal-offers.controller.spec.ts b/src/personal-offers/personal-offers.controller.spec.ts index 6e5ce91d59c7c13504f47bf2dc63d1dd63ae2fa4..50fe471bbea755145c42964d1c2f442f2465f86e 100644 --- a/src/personal-offers/personal-offers.controller.spec.ts +++ b/src/personal-offers/personal-offers.controller.spec.ts @@ -1,23 +1,23 @@ import { Test, TestingModule } from '@nestjs/testing'; -import { PersonalOffersController } from './personal-offers.controller'; -import { PersonalOffersService } from './personal-offers.service'; -import { PersonalOffersServiceMock } from '../../test/mock/services/personalOffers.mock.service'; -import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard'; -import { mockJwtAuthGuard } from '../../test/mock/guards/jwt-auth.mock.guard'; -import { IsPersonalOfferOwnerGuard } from '../users/guards/isPersonalOfferOwner.guard'; -import { mockIsPersonalOfferOwnerGuard } from '../../test/mock/guards/isPersonalOfferOwner.mock.guard'; import { createPersonalOffersDtoDataMock, - updatePersonalOffersDtoDataMock, personalOffersDataMock, + updatePersonalOffersDtoDataMock, } from '../../test/mock/data/personalOffers.mock.data'; -import { UsersService } from '../users/services/users.service'; +import { mockIsPersonalOfferOwnerGuard } from '../../test/mock/guards/isPersonalOfferOwner.mock.guard'; +import { mockJwtAuthGuard } from '../../test/mock/guards/jwt-auth.mock.guard'; +import { PersonalOffersServiceMock } from '../../test/mock/services/personalOffers.mock.service'; +import { StructuresServiceMock } from '../../test/mock/services/structures.mock.service'; import { UsersServiceMock } from '../../test/mock/services/user.mock.service'; +import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard'; import { StructuresService } from '../structures/services/structures.service'; -import { StructuresServiceMock } from '../../test/mock/services/structures.mock.service'; +import { IsPersonalOfferOwnerGuard } from '../users/guards/isPersonalOfferOwner.guard'; +import { UsersService } from '../users/services/users.service'; +import { PersonalOffersController } from './personal-offers.controller'; +import { PersonalOffersService } from './personal-offers.service'; describe('PersonalOffersController', () => { - let controller: PersonalOffersController; + let personalOffersController: PersonalOffersController; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ @@ -43,20 +43,20 @@ describe('PersonalOffersController', () => { .useValue(mockIsPersonalOfferOwnerGuard) .compile(); - controller = module.get<PersonalOffersController>(PersonalOffersController); + personalOffersController = module.get<PersonalOffersController>(PersonalOffersController); }); it('should be defined', () => { - expect(controller).toBeDefined(); + expect(personalOffersController).toBeDefined(); }); describe('find personal offer', () => { it('should get personal offer', async () => { - expect(await controller.find('1234ba0e2ab5775cfc01ed3e')).toBe(personalOffersDataMock[0]); + expect(await personalOffersController.find('1234ba0e2ab5775cfc01ed3e')).toBe(personalOffersDataMock[0]); }); it('should get personal offer does not exist', async () => { try { - await controller.find('abcd'); + await personalOffersController.find('abcd'); // Fail test if above expression doesn't throw anything. expect(true).toBe(false); } catch (e) { @@ -70,7 +70,7 @@ describe('PersonalOffersController', () => { it('should return 204 if personal offer is empty', async () => { const req = { user: { _id: '6036721022462b001334c4bb' } }; try { - await controller.create(req, createPersonalOffersDtoDataMock[3]); + await personalOffersController.create(req, createPersonalOffersDtoDataMock[3]); // Fail test if above expression doesn't throw anything. expect(true).toBe(false); } catch (e) { @@ -80,12 +80,14 @@ describe('PersonalOffersController', () => { }); it('should create personal offer for existing user and structure', async () => { const req = { user: { _id: '6036721022462b001334c4bb' } }; - expect(await controller.create(req, createPersonalOffersDtoDataMock[0])).toEqual(personalOffersDataMock[0]); + expect(await personalOffersController.create(req, createPersonalOffersDtoDataMock[0])).toEqual( + personalOffersDataMock[0] + ); }); it('should return personal offer already exist in the structure', async () => { const req = { user: { _id: '6036721022462b001334c4bb' } }; try { - await controller.create(req, createPersonalOffersDtoDataMock[1]); + await personalOffersController.create(req, createPersonalOffersDtoDataMock[1]); // Fail test if above expression doesn't throw anything. expect(true).toBe(false); } catch (e) { @@ -96,7 +98,7 @@ describe('PersonalOffersController', () => { it('should return structure not found for the personal offer attachment', async () => { const req = { user: { _id: '6036721022462b001334c4bb' } }; try { - await controller.create(req, createPersonalOffersDtoDataMock[2]); + await personalOffersController.create(req, createPersonalOffersDtoDataMock[2]); // Fail test if above expression doesn't throw anything. expect(true).toBe(false); } catch (e) { @@ -107,7 +109,7 @@ describe('PersonalOffersController', () => { it('should return user not found for the personal offer attachment', async () => { const req = { user: { _id: 'unIdQuiExistePasTropTrop' } }; try { - await controller.create(req, createPersonalOffersDtoDataMock[0]); + await personalOffersController.create(req, createPersonalOffersDtoDataMock[0]); // Fail test if above expression doesn't throw anything. expect(true).toBe(false); } catch (e) { @@ -119,13 +121,13 @@ describe('PersonalOffersController', () => { describe('update personal offer', () => { it('should get updated personal offer', async () => { - expect(await controller.update('2345ba0e2ab5775cfc01ed4d', updatePersonalOffersDtoDataMock[1])).toEqual( - personalOffersDataMock[1] - ); + expect( + await personalOffersController.update('2345ba0e2ab5775cfc01ed4d', updatePersonalOffersDtoDataMock[1]) + ).toEqual(personalOffersDataMock[1]); }); it('should get invalid personal offer id', async () => { try { - await controller.update('abcd', updatePersonalOffersDtoDataMock[1]); + await personalOffersController.update('abcd', updatePersonalOffersDtoDataMock[1]); // Fail test if above expression doesn't throw anything. expect(true).toBe(false); } catch (e) { @@ -137,11 +139,11 @@ describe('PersonalOffersController', () => { describe('update personal offer', () => { it('should get deleted personal offer', async () => { - expect(await controller.delete('2345ba0e2ab5775cfc01ed4d')).toEqual(personalOffersDataMock[1]); + expect(await personalOffersController.delete('2345ba0e2ab5775cfc01ed4d')).toEqual(personalOffersDataMock[1]); }); it('should get invalid personal offer id', async () => { try { - await controller.delete('abcd'); + await personalOffersController.delete('abcd'); // Fail test if above expression doesn't throw anything. expect(true).toBe(false); } catch (e) { diff --git a/src/personal-offers/personal-offers.service.spec.ts b/src/personal-offers/personal-offers.service.spec.ts index fba7491954d573b15cd0042c2032ba323e19317d..66dccda5110dc6e26ee1830901139bcfdd0d1499 100644 --- a/src/personal-offers/personal-offers.service.spec.ts +++ b/src/personal-offers/personal-offers.service.spec.ts @@ -12,7 +12,7 @@ import { StructuresService } from './../structures/services/structures.service'; import { PersonalOffersService } from './personal-offers.service'; describe('PersonalOffersService', () => { - let service: PersonalOffersService; + let personalOffersService: PersonalOffersService; const personalOfferModelMock = { findById: jest.fn(), @@ -41,7 +41,7 @@ describe('PersonalOffersService', () => { ], }).compile(); - service = module.get<PersonalOffersService>(PersonalOffersService); + personalOffersService = module.get<PersonalOffersService>(PersonalOffersService); }); afterEach(async () => { @@ -49,21 +49,21 @@ describe('PersonalOffersService', () => { }); it('should be defined', () => { - expect(service).toBeDefined(); + expect(personalOffersService).toBeDefined(); }); describe('findOne', () => { it('should return personal offer', async () => { personalOfferModelMock.findById.mockReturnThis(); personalOfferModelMock.exec.mockResolvedValueOnce(personalOffersDataMock[0]); - expect(await service.findOne('1234ba0e2ab5775cfc01ed3e')).toEqual(personalOffersDataMock[0]); + expect(await personalOffersService.findOne('1234ba0e2ab5775cfc01ed3e')).toEqual(personalOffersDataMock[0]); }); it('should return exception if personal offer is not found for given id', async () => { personalOfferModelMock.findById.mockReturnThis(); personalOfferModelMock.exec.mockResolvedValueOnce(null); let error; try { - await service.findOne('abcd'); + await personalOffersService.findOne('abcd'); } catch (e) { error = e; } @@ -75,7 +75,7 @@ describe('PersonalOffersService', () => { describe('create', () => { it('should create personal offer', async () => { personalOfferModelMock.create.mockResolvedValueOnce(personalOffersDataMock[0]); - expect(await service.create(createPersonalOffersDtoDataMock[0])).toEqual(personalOffersDataMock[0]); + expect(await personalOffersService.create(createPersonalOffersDtoDataMock[0])).toEqual(personalOffersDataMock[0]); }); }); @@ -83,16 +83,16 @@ describe('PersonalOffersService', () => { it('should update personal offer', async () => { personalOfferModelMock.findByIdAndUpdate.mockReturnThis(); personalOfferModelMock.exec.mockResolvedValueOnce(personalOffersDataMock[1]); - expect(await service.update('2345ba0e2ab5775cfc01ed4d', updatePersonalOffersDtoDataMock[1])).toEqual( - personalOffersDataMock[1] - ); + expect( + await personalOffersService.update('2345ba0e2ab5775cfc01ed4d', updatePersonalOffersDtoDataMock[1]) + ).toEqual(personalOffersDataMock[1]); }); it('should return exception if personal offer is not found for given id', async () => { personalOfferModelMock.findById.mockReturnThis(); personalOfferModelMock.exec.mockResolvedValueOnce(null); let error; try { - await service.update('abcd', updatePersonalOffersDtoDataMock[1]); + await personalOffersService.update('abcd', updatePersonalOffersDtoDataMock[1]); } catch (e) { error = e; } @@ -105,14 +105,14 @@ describe('PersonalOffersService', () => { it('should update personal offer', async () => { personalOfferModelMock.findByIdAndDelete.mockReturnThis(); personalOfferModelMock.exec.mockResolvedValueOnce(personalOffersDataMock[0]); - expect(await service.delete('2345ba0e2ab5775cfc01ed4d')).toEqual(personalOffersDataMock[0]); + expect(await personalOffersService.delete('2345ba0e2ab5775cfc01ed4d')).toEqual(personalOffersDataMock[0]); }); it('should return exception if personal offer is not found for given id', async () => { personalOfferModelMock.findById.mockReturnThis(); personalOfferModelMock.exec.mockResolvedValueOnce(null); let error; try { - await service.delete('abcd'); + await personalOffersService.delete('abcd'); } catch (e) { error = e; } diff --git a/src/posts/posts.controller.spec.ts b/src/posts/posts.controller.spec.ts index 6aedad0dd6f8f6759343881c9722bc596c662c59..6318983820eb9d566acf9d535bb4588fdff769bb 100644 --- a/src/posts/posts.controller.spec.ts +++ b/src/posts/posts.controller.spec.ts @@ -1,13 +1,13 @@ import { HttpModule, HttpService } from '@nestjs/axios'; import { Test, TestingModule } from '@nestjs/testing'; +import { AxiosResponse } from 'axios'; import { of } from 'rxjs'; import { ConfigurationModule } from '../configuration/configuration.module'; import { PostsController } from './posts.controller'; import { PostsService } from './posts.service'; -import { AxiosResponse } from 'axios'; describe('PostsController', () => { - let controller: PostsController; + let postsController: PostsController; const httpServiceMock = { get: jest.fn(), @@ -36,11 +36,11 @@ describe('PostsController', () => { controllers: [PostsController], }).compile(); - controller = module.get<PostsController>(PostsController); + postsController = module.get<PostsController>(PostsController); }); it('should be defined', () => { - expect(controller).toBeDefined(); + expect(postsController).toBeDefined(); }); describe('findAll', () => { @@ -196,7 +196,7 @@ describe('PostsController', () => { config: {}, }; jest.spyOn(httpServiceMock, 'get').mockImplementationOnce(() => of(result)); - const response = await controller.findAll(query); + const response = await postsController.findAll(query); expect(response.posts.length).toEqual(3); expect(response.meta.pagination.limit).toEqual(15); expect(response.meta.pagination.page).toEqual(1); @@ -350,7 +350,7 @@ describe('PostsController', () => { url: 'http://localhost:2368/tag/etudes/', }, ]); - const result = await controller.findAllTags(); + const result = await postsController.findAllTags(); expect(result.commune.length).toBe(3); expect(result.others.length).toBe(1); expect(result.public.length).toBe(2); @@ -418,7 +418,7 @@ describe('PostsController', () => { }; httpServiceMock.get.mockImplementationOnce(() => of(axiosResult)); postServiceMock.formatPosts.mockImplementationOnce(() => data); - const result = await (await controller.getPostbyId('61c4847b0ff4550001505090')).toPromise(); + const result = await (await postsController.getPostbyId('61c4847b0ff4550001505090')).toPromise(); expect(result).toStrictEqual({ posts: [data] }); }); }); diff --git a/src/posts/posts.service.spec.ts b/src/posts/posts.service.spec.ts index 9b2382d58117088dccb2fdb1154b1d27f9d06059..39b93f32aee71e46e731f9b2bfad9aad05844587 100644 --- a/src/posts/posts.service.spec.ts +++ b/src/posts/posts.service.spec.ts @@ -1,14 +1,14 @@ import { HttpModule } from '@nestjs/axios'; import { Test, TestingModule } from '@nestjs/testing'; +import * as _ from 'lodash'; import { ConfigurationModule } from '../configuration/configuration.module'; import { TagEnum } from './enums/tag.enum'; import { PostsService } from './posts.service'; -import { Tag } from './schemas/tag.schema'; -import * as _ from 'lodash'; import { Post } from './schemas/post.schema'; +import { Tag } from './schemas/tag.schema'; describe('PostsService', () => { - let service: PostsService; + let postsService: PostsService; // let configService: ConfigurationServiceMock; const locationtags = [ @@ -212,38 +212,38 @@ describe('PostsService', () => { providers: [PostsService], }).compile(); - service = module.get<PostsService>(PostsService); - jest.spyOn(service, 'getTags').mockImplementationOnce(async (): Promise<Tag[]> => tagsData); + postsService = module.get<PostsService>(PostsService); + jest.spyOn(postsService, 'getTags').mockImplementationOnce(async (): Promise<Tag[]> => tagsData); }); it('should be defined', () => { - expect(service).toBeDefined(); + expect(postsService).toBeDefined(); }); it('should get tags', async () => { - expect(await service.getTags()).toEqual(tagsData); + expect(await postsService.getTags()).toEqual(tagsData); }); it('should get location tags', async () => { - expect(await service.getLocationTags()).toEqual(locationtags); + expect(await postsService.getLocationTags()).toEqual(locationtags); }); it('should get public tags', async () => { - expect(await service.getPublicTags()).toEqual(publictags); + expect(await postsService.getPublicTags()).toEqual(publictags); }); it('should get regular tags', async () => { - expect(await service.getRegularTags()).toEqual([otherTags[1], otherTags[2], otherTags[0]]); + expect(await postsService.getRegularTags()).toEqual([otherTags[1], otherTags[2], otherTags[0]]); }); describe('arraymove', () => { it('should order tags for display: A La Une tag should be set to first index', () => { const dataCopy = [...otherTags]; - service.arraymove(dataCopy, _.findIndex(dataCopy, { slug: TagEnum.aLaUne }), 0); + postsService.arraymove(dataCopy, _.findIndex(dataCopy, { slug: TagEnum.aLaUne }), 0); expect(dataCopy).toEqual([otherTags[1], otherTags[0], otherTags[2]]); }); it('should order tags for display: Info tag should be set to second index', () => { const dataCopy = [...otherTags]; - expect(service.arraymove(dataCopy, _.findIndex(dataCopy, { slug: TagEnum.infos }), 1)).toEqual([ + expect(postsService.arraymove(dataCopy, _.findIndex(dataCopy, { slug: TagEnum.infos }), 1)).toEqual([ otherTags[0], otherTags[2], otherTags[1], @@ -251,8 +251,8 @@ describe('PostsService', () => { }); it('should order tags for display: A La Une tag should be set to first index and Info to second', () => { const dataCopy = [...otherTags]; - service.arraymove(dataCopy, _.findIndex(dataCopy, { slug: TagEnum.aLaUne }), 0); - expect(service.arraymove(dataCopy, _.findIndex(dataCopy, { slug: TagEnum.infos }), 1)).toEqual([ + postsService.arraymove(dataCopy, _.findIndex(dataCopy, { slug: TagEnum.aLaUne }), 0); + expect(postsService.arraymove(dataCopy, _.findIndex(dataCopy, { slug: TagEnum.infos }), 1)).toEqual([ otherTags[1], otherTags[2], otherTags[0], @@ -312,7 +312,7 @@ describe('PostsService', () => { const result = { ...postToFormat }; result.excerpt = 'Inconnu'; result.feature_image = 'https://localhost/blog/content/images/2021/12/dacc-4.png'; - expect(service.formatPosts(objCp)).toEqual(result); + expect(postsService.formatPosts(objCp)).toEqual(result); }); it('should format post with custom expert', () => { const objCp = { ...postToFormat }; @@ -320,7 +320,7 @@ describe('PostsService', () => { const result = { ...postToFormat }; result.custom_excerpt = 'Toto'; result.feature_image = 'https://localhost/blog/content/images/2021/12/dacc-4.png'; - expect(service.formatPosts(objCp)).toEqual(result); + expect(postsService.formatPosts(objCp)).toEqual(result); }); }); }); diff --git a/src/structures/services/structures-export.service.spec.ts b/src/structures/services/structures-export.service.spec.ts index 4198874c100bf0a49fa22549284a6fa333155c96..d659ae40fc277efded2f46048606fb30b2e0109a 100644 --- a/src/structures/services/structures-export.service.spec.ts +++ b/src/structures/services/structures-export.service.spec.ts @@ -1,11 +1,11 @@ -import { Test, TestingModule } from '@nestjs/testing'; import { getModelToken } from '@nestjs/mongoose'; -import { StructuresExportService } from './structures-export.service'; +import { Test, TestingModule } from '@nestjs/testing'; import { Model, Query } from 'mongoose'; -import { StructureDocument } from '../schemas/structure.schema'; -import { StructureFormatted } from '../interfaces/structure-formatted.interface'; import { mockFormattedStructures } from '../../../test/mock/services/structures-export.mock.service'; +import { StructureFormatted } from '../interfaces/structure-formatted.interface'; +import { StructureDocument } from '../schemas/structure.schema'; import { StructureCategories } from '../schemas/structureCategories.schema'; +import { StructuresExportService } from './structures-export.service'; import { StructuresService } from './structures.service'; const mockStructureModel = { @@ -140,7 +140,7 @@ function createMockedStructure(overrides: Partial<StructureDocument> = {}) { } describe('StructuresExportService', () => { - let service: StructuresExportService; + let structureExportService: StructuresExportService; let structureModel: Model<StructureDocument>; beforeEach(async () => { @@ -160,7 +160,7 @@ describe('StructuresExportService', () => { ], }).compile(); - service = module.get<StructuresExportService>(StructuresExportService); + structureExportService = module.get<StructuresExportService>(StructuresExportService); structureModel = module.get<Model<StructureDocument>>(getModelToken('Structure')); }); @@ -177,7 +177,7 @@ describe('StructuresExportService', () => { jest.spyOn(structureModel, 'find').mockReturnValueOnce(mockQuery); const expectedFormattedStructure: StructureFormatted = mockFormattedStructures[0]; - const result: StructureFormatted[] = await service.exportFormatted(); + const result: StructureFormatted[] = await structureExportService.exportFormatted(); expect(structureModel.find).toHaveBeenCalledWith({ deletedAt: { $exists: false }, @@ -190,7 +190,7 @@ describe('StructuresExportService', () => { describe('checkPublic', () => { const invokeCheckPublic = (age: string[], handicaps: string[], languages: string[], other: string[]) => - (service as any).checkPublic(age, handicaps, languages, other); // any to bypass ts access checks on private method + (structureExportService as any).checkPublic(age, handicaps, languages, other); // any to bypass ts access checks on private method it('should return an empty string when no parameters are provided', () => { const result = invokeCheckPublic([], [], [], []); expect(result).toEqual(''); @@ -225,7 +225,7 @@ describe('StructuresExportService', () => { describe('checkAccessConditions', () => { const invokeCheckAccessConditions = (accessModality: string[]) => - (service as any).checkAccessConditions(accessModality); // any to bypass ts access checks on private method + (structureExportService as any).checkAccessConditions(accessModality); // any to bypass ts access checks on private method it('should return an empty string when no access modality is provided', () => { const result = invokeCheckAccessConditions([]); @@ -246,7 +246,8 @@ describe('StructuresExportService', () => { }); describe('formatServices', () => { - const invokeFormatServices = (structCat: StructureCategories) => (service as any).formatServices(structCat); // any to bypass ts access checks on private method + const invokeFormatServices = (structCat: StructureCategories) => + (structureExportService as any).formatServices(structCat); // any to bypass ts access checks on private method it('should return an empty string when no structure categories are provided', () => { const result = invokeFormatServices(null); @@ -286,7 +287,7 @@ describe('StructuresExportService', () => { describe('formatAddress', () => { const invokeFormatAddress = (address: { numero?: string; street: string }) => - (service as any).formatAddress(address); // any to bypass ts access checks on private method + (structureExportService as any).formatAddress(address); // any to bypass ts access checks on private method it('should return the formatted address with street only when no numero is provided', () => { const address = { street: 'Rue Robert et Reynier' }; @@ -303,7 +304,7 @@ describe('StructuresExportService', () => { describe('convertToOSMFormat', () => { const invokeConvertToOSMFormat = (openingHours: Record<string, any>) => - (service as any).convertToOSMFormat(openingHours); // any to bypass ts access checks on private method + (structureExportService as any).convertToOSMFormat(openingHours); // any to bypass ts access checks on private method it('should return empty string when openingHours is empty', () => { const openingHours = { diff --git a/src/structures/services/structures-import.service.spec.ts b/src/structures/services/structures-import.service.spec.ts index 4fce87cccc07c72c5032771a96e749fd0ab836d7..28ef5f1bb6a542cfb7b77466be5f959908a8e2f1 100644 --- a/src/structures/services/structures-import.service.spec.ts +++ b/src/structures/services/structures-import.service.spec.ts @@ -1,14 +1,14 @@ -import { Test, TestingModule } from '@nestjs/testing'; -import { getModelToken } from '@nestjs/mongoose'; -import { StructuresImportService } from './structures-import.service'; -import { of } from 'rxjs'; -import { DataGouvStructure } from '../interfaces/data-gouv-structure.interface'; import { HttpService } from '@nestjs/axios'; +import { getModelToken } from '@nestjs/mongoose'; +import { Test, TestingModule } from '@nestjs/testing'; import { AxiosResponse } from 'axios'; +import { of } from 'rxjs'; import { mockGouvStructure, mockGouvStructureToResinFormat } from '../../../test/mock/data/gouvStructures.mock.data'; +import { DataGouvStructure } from '../interfaces/data-gouv-structure.interface'; +import { StructuresImportService } from './structures-import.service'; describe('StructuresImportService', () => { - let service: StructuresImportService; + let structuresImportService: StructuresImportService; let httpService: HttpService; beforeEach(async () => { @@ -32,7 +32,7 @@ describe('StructuresImportService', () => { ], }).compile(); - service = module.get<StructuresImportService>(StructuresImportService); + structuresImportService = module.get<StructuresImportService>(StructuresImportService); httpService = module.get<HttpService>(HttpService); }); @@ -47,13 +47,17 @@ describe('StructuresImportService', () => { }; const saveSpy = jest.fn(); const mockStructureModel = jest.fn().mockImplementation(() => ({ save: saveSpy })); - (service as any).structureModel = mockStructureModel; + (structuresImportService as any).structureModel = mockStructureModel; - const formatToResinSchemaSpy = jest.spyOn(service as any, 'formatToResinSchema').mockResolvedValueOnce('called'); - const doesAlreadyExistSpy = jest.spyOn(service as any, 'doesAlreadyExist').mockResolvedValueOnce(false); + const formatToResinSchemaSpy = jest + .spyOn(structuresImportService as any, 'formatToResinSchema') + .mockResolvedValueOnce('called'); + const doesAlreadyExistSpy = jest + .spyOn(structuresImportService as any, 'doesAlreadyExist') + .mockResolvedValueOnce(false); jest.spyOn(httpService, 'get').mockImplementationOnce(() => of(mockedAxiosResponse)); - await service.importDataGouvStructures(); + await structuresImportService.importDataGouvStructures(); expect(httpService.get).toBeCalled(); expect(formatToResinSchemaSpy).toBeCalled(); @@ -64,7 +68,7 @@ describe('StructuresImportService', () => { describe('formatToResinSchema', () => { it('should transform data.gouv structures to resin format', async () => { - const result = await service['formatToResinSchema'](mockGouvStructure); + const result = await structuresImportService['formatToResinSchema'](mockGouvStructure); expect(result).toEqual(mockGouvStructureToResinFormat); }); }); diff --git a/src/structures/services/structures-search.service.spec.ts b/src/structures/services/structures-search.service.spec.ts index f5b2043039de5ba41ea1df9999d4e0dbdce33404..65b2a8f866be15d56a65f176229e7b3b79e996af 100644 --- a/src/structures/services/structures-search.service.spec.ts +++ b/src/structures/services/structures-search.service.spec.ts @@ -7,7 +7,7 @@ import { SearchModule } from '../../search/search.module'; import { StructuresSearchService } from './structures-search.service'; import { StructuresService } from './structures.service'; describe('StructuresSearchService', () => { - let service: StructuresSearchService; + let structureSearchService: StructuresSearchService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ @@ -21,90 +21,90 @@ describe('StructuresSearchService', () => { ], }).compile(); - service = module.get<StructuresSearchService>(StructuresSearchService); - service['index'] = 'structures-unit-test'; - await service.dropIndex(); - await service.createStructureIndex(); + structureSearchService = module.get<StructuresSearchService>(StructuresSearchService); + structureSearchService['index'] = 'structures-unit-test'; + await structureSearchService.dropIndex(); + await structureSearchService.createStructureIndex(); // init str const structuresForSearchService = new StructuresForSearchServiceMock(); const structures = structuresForSearchService.findAll(); await Promise.all( structures.map((structure) => { - service.indexStructure(structure); + structureSearchService.indexStructure(structure); }) ); // wait for the new structures to be indexed before search - await service.refreshIndexStructure(); + await structureSearchService.refreshIndexStructure(); await new Promise((r) => setTimeout(r, 2000)); }, 10000); it('should be defined', () => { - expect(service).toBeDefined(); + expect(structureSearchService).toBeDefined(); }); it('should find maisons de la métropole', async () => { - const res = await service.search('maison de la'); + const res = await structureSearchService.search('maison de la'); //Logger.log(JSON.stringify(res)); expect(res[0].structureName).toContain('Maison de la Métropole'); expect(res[1].structureName).toContain('Maison de la Métropole'); }); it('should find metropole', async () => { - const res = await service.search('metropole'); + const res = await structureSearchService.search('metropole'); expect(res[0].structureName).toContain('Métropole'); }); it('should find structure with stopword "son"', async () => { - const res = await service.search('son'); + const res = await structureSearchService.search('son'); expect(res[0].structureName).toContain('Le Son du Clic'); }); it('should find structure with stopword "mais"', async () => { - const res = await service.search('mais'); + const res = await structureSearchService.search('mais'); expect(res[0].structureName.toLowerCase()).toContain('maison'); }); it('should find structure with stopword "le"', async () => { - const res = await service.search('le'); + const res = await structureSearchService.search('le'); expect(res.length).toBeGreaterThanOrEqual(1); }); it('should find structure with partial word "oull"', async () => { - const res = await service.search('oull'); + const res = await structureSearchService.search('oull'); expect(res[0].structureName.toLowerCase()).toContain('oullins'); }); it('should find structure with partial word "vill"', async () => { - const res = await service.search('vill'); + const res = await structureSearchService.search('vill'); expect(res[0].structureName.toLowerCase()).toContain('villeurbanne'); }); it('should find structure with partial word "asso"', async () => { - const res = await service.search('asso'); + const res = await structureSearchService.search('asso'); Logger.log(JSON.stringify(res)); expect(res[0].structureName.toLowerCase()).toContain('association'); }); it('should find text in description', async () => { - const res = await service.search('liseuse'); + const res = await structureSearchService.search('liseuse'); expect(res.length).toBe(1); expect(res[0].structureName).toContain("Médiathèque d'Ecully"); }); it('should not find text in description when search by name', async () => { - const res = await service.search('liseuse', ['structureName']); + const res = await structureSearchService.search('liseuse', ['structureName']); expect(res.length).toBe(0); }); it('should find structure when search by name', async () => { - const res = await service.search('le son', ['structureName']); + const res = await structureSearchService.search('le son', ['structureName']); expect(res[0].structureName).toContain('Le Son du Clic'); }); it('should drop index', async () => { - const res = await service.dropIndex(); + const res = await structureSearchService.dropIndex(); expect(res).toBeTruthy(); }); }); diff --git a/src/structures/services/structures.service.spec.ts b/src/structures/services/structures.service.spec.ts index b74a7aee18f42a6f50ae6f6e4bf2d9097cad4a11..9059b869b235313fc1630de4cfbd83eadcaed0ac 100644 --- a/src/structures/services/structures.service.spec.ts +++ b/src/structures/services/structures.service.spec.ts @@ -238,7 +238,7 @@ const jobServiceMock = { }; describe('StructuresService', () => { - let service: StructuresService; + let structureService: StructuresService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ @@ -278,19 +278,19 @@ describe('StructuresService', () => { ], }).compile(); - service = module.get<StructuresService>(StructuresService); - service['structuresSearchService']['index'] = 'structures-unit-test'; + structureService = module.get<StructuresService>(StructuresService); + structureService['structuresSearchService']['index'] = 'structures-unit-test'; }); it('should be defined', () => { - expect(service).toBeDefined(); + expect(structureService).toBeDefined(); }); it('should Initiate structure index', async () => { const spyerIndex = jest.spyOn(structuresSearchServiceMock, 'indexStructure'); const spyerDrop = jest.spyOn(structuresSearchServiceMock, 'dropIndex'); const spyerCreate = jest.spyOn(structuresSearchServiceMock, 'createStructureIndex'); - await service.initiateStructureIndex(); + await structureService.initiateStructureIndex(); expect(spyerCreate).toBeCalledTimes(1); expect(spyerDrop).toBeCalledTimes(1); expect(spyerIndex).toBeCalledTimes(1); @@ -370,19 +370,19 @@ describe('StructuresService', () => { ]); it('should find 1 structure', async () => { - const res = await service.searchForStructures('a', [[{ nbPrinters: '1' }], []]); + const res = await structureService.searchForStructures('a', [[{ nbPrinters: '1' }], []]); expect(res.length).toBe(1); }); it('should find 1 structure', async () => { - const res = await service.searchForStructures('a', [[{ nbPrinters: '1' }, { '': 'baseSkills' }], []]); + const res = await structureService.searchForStructures('a', [[{ nbPrinters: '1' }, { '': 'baseSkills' }], []]); expect(res.length).toBe(1); }); it('should find 1 structure', async () => { - const res = await service.searchForStructures('a', [[{ '': 'baseSkills' }], []]); + const res = await structureService.searchForStructures('a', [[{ '': 'baseSkills' }], []]); expect(res.length).toBe(1); }); it('should find 1 structure', async () => { - const res = await service.searchForStructures('a'); + const res = await structureService.searchForStructures('a'); expect(res.length).toBe(1); }); }); @@ -391,7 +391,7 @@ describe('StructuresService', () => { it('should return invalid profile', async () => { const structure = structureMockDto; try { - await service.create('test@test.com', structure); + await structureService.create('test@test.com', structure); expect(true).toBe(false); } catch (e) { expect(e.message).toEqual('Invalid profile'); @@ -401,45 +401,45 @@ describe('StructuresService', () => { }); it('should set structure to be deleted', async () => { - const res = await service.setToBeDeleted(userDetails[0], structuresDocumentDataMock[0]); + const res = await structureService.setToBeDeleted(userDetails[0], structuresDocumentDataMock[0]); expect(res.toBeDeletedAt).toBeTruthy(); }); it('should cancel structure delete', async () => { - const res = await service.cancelDelete(userDetails[0], structuresDocumentDataMock[0]); + const res = await structureService.cancelDelete(userDetails[0], structuresDocumentDataMock[0]); expect(res.toBeDeletedAt).toBeNull(); }); it('should search structure', () => { const filters = [{ nbPrinters: '1' }]; - let res = service.search('', filters); + let res = structureService.search('', filters); expect(res).toBeTruthy(); - res = service.search(null, filters); + res = structureService.search(null, filters); expect(res).toBeTruthy(); - res = service.search(null); + res = structureService.search(null); expect(res).toBeTruthy(); }); describe('findAll', () => { it('should find all structures', () => { - expect(service.findAll()).toBeTruthy(); + expect(structureService.findAll()).toBeTruthy(); }); it('should find all deleted structures', () => { - expect(service.findAll(true)).toBeTruthy(); + expect(structureService.findAll(true)).toBeTruthy(); }); it('should find all unclaimed structures', () => { - expect(service.findAllUnclaimed()).toBeTruthy(); + expect(structureService.findAllUnclaimed()).toBeTruthy(); }); it('should find all formatted structures', () => { - expect(service.findConsentingStructures(null)).toBeTruthy(); + expect(structureService.findConsentingStructures(null)).toBeTruthy(); }); }); it('should populate ES', () => { - expect(service.populateES()).toBeTruthy(); + expect(structureService.populateES()).toBeTruthy(); }); describe('getAllDataConsentPendingStructures', () => { @@ -469,7 +469,7 @@ describe('StructuresService', () => { createdAt: new Date('2022-05-25T09:48:28.824Z'), } as IUser; jest - .spyOn(service, 'findOne') + .spyOn(structureService, 'findOne') .mockResolvedValueOnce({ _id: new Types.ObjectId('61e9260b2ac971550065e261'), coord: [4.844309, 45.865288], @@ -491,7 +491,7 @@ describe('StructuresService', () => { updatedAt: new Date('Thu Jan 20 2022 10:06:19 GMT+0100 (heure normale d’Europe centrale)'), dataShareConsentDate: new Date(), } as StructureDocument); - const res = await service.getAllDataConsentPendingStructures(user); + const res = await structureService.getAllDataConsentPendingStructures(user); expect(res.length).toBe(1); }); it('should get no consent', async () => { @@ -520,7 +520,7 @@ describe('StructuresService', () => { createdAt: new Date('2022-05-25T09:48:28.824Z'), } as IUser; jest - .spyOn(service, 'findOne') + .spyOn(structureService, 'findOne') .mockResolvedValueOnce({ _id: new Types.ObjectId('61e9260b2ac971550065e261'), coord: [4.844309, 45.865288], @@ -543,31 +543,31 @@ describe('StructuresService', () => { updatedAt: new Date('Thu Jan 20 2022 10:06:19 GMT+0100 (heure normale d’Europe centrale)'), dataShareConsentDate: new Date(), } as StructureDocument); - const res = await service.getAllDataConsentPendingStructures(user); + const res = await structureService.getAllDataConsentPendingStructures(user); expect(res.length).toBe(0); }); }); it('should report structure Error', () => { - let res = service.reportStructureError('6093ba0e2ab5775cfc01ed3e', ''); + let res = structureService.reportStructureError('6093ba0e2ab5775cfc01ed3e', ''); expect(res).toBeTruthy(); - res = service.reportStructureError(null, ''); + res = structureService.reportStructureError(null, ''); expect(res).toBeTruthy(); }); describe('addPersonalOffer', () => { const personalOfferDocumentMock: PersonalOfferDocument = personalOffersDataMock[0] as PersonalOfferDocument; it('should add personal offer to the structure', async () => { - jest.spyOn(service, 'findOne').mockResolvedValue(structuresDocumentDataMock[0]); + jest.spyOn(structureService, 'findOne').mockResolvedValue(structuresDocumentDataMock[0]); const expectedResult = { ...structuresDocumentDataMock[0], personalOffers: [personalOfferDocumentMock] }; - expect(await service.addPersonalOffer('6093ba0e2ab5775cfc01ed3e', personalOfferDocumentMock)).toEqual( + expect(await structureService.addPersonalOffer('6093ba0e2ab5775cfc01ed3e', personalOfferDocumentMock)).toEqual( expectedResult ); }); it('should return exception if structure is not found for given id', async () => { - jest.spyOn(service, 'findOne').mockResolvedValue(null); + jest.spyOn(structureService, 'findOne').mockResolvedValue(null); try { - await service.addPersonalOffer('abcd', personalOfferDocumentMock); + await structureService.addPersonalOffer('abcd', personalOfferDocumentMock); // Fail test if above expression doesn't throw anything. expect(true).toBe(false); } catch (e) { @@ -576,9 +576,9 @@ describe('StructuresService', () => { } }); it('should return exception if personal offer already exists in the structure', async () => { - jest.spyOn(service, 'findOne').mockResolvedValue(structuresDocumentDataMock[1]); + jest.spyOn(structureService, 'findOne').mockResolvedValue(structuresDocumentDataMock[1]); try { - await service.addPersonalOffer('6093ba0e2ab5775cfc01ed3e', personalOfferDocumentMock); + await structureService.addPersonalOffer('6093ba0e2ab5775cfc01ed3e', personalOfferDocumentMock); // Fail test if above expression doesn't throw anything. expect(true).toBe(false); } catch (e) { @@ -594,26 +594,26 @@ describe('StructuresService', () => { }); it('getCNFSStructuress(): should return 2 structures from the mock containing 4 structures', async () => { - expect((await service.getCNFSStructures()).length).toBe(2); + expect((await structureService.getCNFSStructures()).length).toBe(2); }); it('bindOneCNFSStructure(): should update ONE structure', async () => { const mockSetCNFSid = jest.fn().mockResolvedValue(mockResinStructures[0]); - jest.spyOn(service, 'findOne').mockResolvedValue(mockResinStructures[0] as StructureDocument); - jest.spyOn(service, 'setCNFSid').mockImplementation(mockSetCNFSid); + jest.spyOn(structureService, 'findOne').mockResolvedValue(mockResinStructures[0] as StructureDocument); + jest.spyOn(structureService, 'setCNFSid').mockImplementation(mockSetCNFSid); mockStructureModel.findByIdAndUpdate.mockReturnThis(); mockStructureModel.exec.mockResolvedValueOnce(mockResinStructures[0]); - expect(await service.bindOneCNFSStructure('mockId')).toBe('A match has been found, updating CNFSid'); + expect(await structureService.bindOneCNFSStructure('mockId')).toBe('A match has been found, updating CNFSid'); }); it('bindOneCNFSStructure(): should update ZERO structure, no match', async () => { - jest.spyOn(service, 'findOne').mockReturnThis(); - jest.spyOn(service, 'update').mockResolvedValue(mockResinStructures[2]); - expect(await service.bindOneCNFSStructure('mockId')).toBe('No match found'); + jest.spyOn(structureService, 'findOne').mockReturnThis(); + jest.spyOn(structureService, 'update').mockResolvedValue(mockResinStructures[2]); + expect(await structureService.bindOneCNFSStructure('mockId')).toBe('No match found'); }); it('bindCNFSids(): should update 2 structures (matching phone and mail)', async () => { const mockSetCNFSid = jest.fn().mockResolvedValue(mockResinStructures[0]); - jest.spyOn(service, 'findAll').mockResolvedValue(mockResinStructures as StructureDocument[]); - jest.spyOn(service, 'setCNFSid').mockImplementation(mockSetCNFSid); - expect(await service.bindCNFSids()).toBe(`2 structures affected`); + jest.spyOn(structureService, 'findAll').mockResolvedValue(mockResinStructures as StructureDocument[]); + jest.spyOn(structureService, 'setCNFSid').mockImplementation(mockSetCNFSid); + expect(await structureService.bindCNFSids()).toBe(`2 structures affected`); expect(mockSetCNFSid).toHaveBeenCalledTimes(2); }); }); @@ -622,7 +622,7 @@ describe('StructuresService', () => { it('should restore a structure', async () => { mockStructureModel.findByIdAndUpdate.mockReturnThis(); mockStructureModel.exec.mockImplementation(() => null); - await service.restoreStructure('someId'); + await structureService.restoreStructure('someId'); expect(mockStructureModel.findByIdAndUpdate).toBeCalled(); }); }); @@ -657,7 +657,7 @@ describe('StructuresService', () => { }, ], }; - const result = await service.searchAddress(data); + const result = await structureService.searchAddress(data); expect(httpServiceMock.get).toHaveBeenCalledTimes(2); expect(result).toEqual(expectedResult); diff --git a/src/structures/structures.controller.spec.ts b/src/structures/structures.controller.spec.ts index fe2a5a02c076039601d8faa3b9dbab313504eb7e..d2ea4b6fdc541e3eb352925035ea4920af41c51c 100644 --- a/src/structures/structures.controller.spec.ts +++ b/src/structures/structures.controller.spec.ts @@ -1,9 +1,14 @@ import { HttpService } from '@nestjs/axios'; import { HttpStatus } from '@nestjs/common'; +import { getModelToken } from '@nestjs/mongoose'; import { Test, TestingModule } from '@nestjs/testing'; import { Types } from 'mongoose'; import { CategoriesServiceMock } from '../../test/mock/services/categories.mock.service'; import { HttpServiceMock } from '../../test/mock/services/http.mock.service'; +import { + StructuresExportServiceMock, + mockFormattedStructures, +} from '../../test/mock/services/structures-export.mock.service'; import { StructuresServiceMock } from '../../test/mock/services/structures.mock.service'; import { TempUserServiceMock } from '../../test/mock/services/tempUser.mock.service'; import { UsersServiceMock } from '../../test/mock/services/user.mock.service'; @@ -11,24 +16,20 @@ import { CategoriesService } from '../categories/services/categories.service'; import { PersonalOffersService } from '../personal-offers/personal-offers.service'; import { TempUserService } from '../temp-user/temp-user.service'; import { UserRole } from '../users/enum/user-role.enum'; +import { JobDocument } from '../users/schemas/job.schema'; import { UsersService } from '../users/services/users.service'; import { PersonalOffersServiceMock } from './../../test/mock/services/personalOffers.mock.service'; import { PersonalOffer, PersonalOfferDocument } from './../personal-offers/schemas/personal-offer.schema'; import { CreateStructureDto } from './dto/create-structure.dto'; -import { StructuresService } from './services/structures.service'; -import { StructuresController } from './structures.controller'; -import { StructuresExportService } from './services/structures-export.service'; -import { - StructuresExportServiceMock, - mockFormattedStructures, -} from '../../test/mock/services/structures-export.mock.service'; import { StructureFormatted } from './interfaces/structure-formatted.interface'; -import { JobDocument } from '../users/schemas/job.schema'; -import { StructuresImportService } from './services/structures-import.service'; -import { getModelToken } from '@nestjs/mongoose'; import { Structure } from './schemas/structure.schema'; +import { StructuresExportService } from './services/structures-export.service'; +import { StructuresImportService } from './services/structures-import.service'; +import { StructuresService } from './services/structures.service'; +import { StructuresController } from './structures.controller'; + describe('StructuresController', () => { - let controller: StructuresController; + let structuresController: StructuresController; let usersService: UsersService; let structuresExportService: StructuresExportService; let personalOffersService: PersonalOffersService; @@ -73,18 +74,18 @@ describe('StructuresController', () => { }, ], }).compile(); - controller = module.get<StructuresController>(StructuresController); + structuresController = module.get<StructuresController>(StructuresController); usersService = module.get<UsersService>(UsersService); structuresExportService = module.get<StructuresExportService>(StructuresExportService); personalOffersService = module.get<PersonalOffersService>(PersonalOffersService); }); it('should be defined', () => { - expect(controller).toBeDefined(); + expect(structuresController).toBeDefined(); }); it('should get structure coordinates', async () => { - const coords = controller.getCoordinates('Lyon'); + const coords = structuresController.getCoordinates('Lyon'); expect(coords).toBeTruthy(); }); @@ -93,13 +94,13 @@ describe('StructuresController', () => { userEmail: 'admin@admin.com', structure: null, }; - const res = controller.create(structure); + const res = structuresController.create(structure); expect(res).toBeTruthy(); }); it('should update structure after ownerVerify', async () => { const structureId = '1'; - const res = controller.updateAfterOwnerVerify(structureId); + const res = structuresController.updateAfterOwnerVerify(structureId); expect(res).toBeTruthy(); }); @@ -108,7 +109,7 @@ describe('StructuresController', () => { const structure = structureService.findOne(new Types.ObjectId('6093ba0e2ab5775cfc01ed3e')); const structureId = '1'; - const res = await controller.update(structureId, { + const res = await structuresController.update(structureId, { deletedAt: null, remoteAccompaniment: null, dataShareConsentDate: null, @@ -119,7 +120,7 @@ describe('StructuresController', () => { }); it('should get all structure', async () => { - const res = await controller.findAll(); + const res = await structuresController.findAll(); expect(res.length).toBe(2); }); @@ -127,25 +128,25 @@ describe('StructuresController', () => { const mockResult: StructureFormatted[] = mockFormattedStructures; jest.spyOn(structuresExportService, 'exportFormatted').mockResolvedValueOnce(mockResult); - const result: StructureFormatted[] = await controller.findAllFormatted(); + const result: StructureFormatted[] = await structuresController.findAllFormatted(); expect(result).toEqual(mockResult); }); it('should search structure', async () => { - const res = controller.search(null, null); + const res = structuresController.search(null, null); expect(res).toBeTruthy(); }); it('should reset Search Index', async () => { - const res = controller.resetES(); + const res = structuresController.resetES(); expect(res).toBeTruthy(); }); it('should claim structure', async () => { const userMock = new UsersServiceMock(); const user = userMock.findOne('pauline.dupont@mii.com'); - const res = controller.claim('1', { + const res = structuresController.claim('1', { phone: null, resetPasswordToken: null, changeEmailToken: null, @@ -179,27 +180,27 @@ describe('StructuresController', () => { }); it('should search an address', async () => { - const res = controller.searchAddress({ searchQuery: 'Rue Alphonse Daudet' }); + const res = structuresController.searchAddress({ searchQuery: 'Rue Alphonse Daudet' }); expect(res).toBeTruthy(); }); describe('find(structureId)', () => { it('should find structure', async () => { - let res = controller.find({ user: {} }, '6093ba0e2ab5775cfc01ed3e'); + let res = structuresController.find({ user: {} }, '6093ba0e2ab5775cfc01ed3e'); expect(res).toBeTruthy(); - res = controller.find({ user: {} }, ''); + res = structuresController.find({ user: {} }, ''); expect(res).toBeTruthy(); }); it('should find deleted structure as an admin', async () => { - const response = controller.find({ user: { role: UserRole.admin } }, '6093ba0e2ab5775cfc01ed33'); + const response = structuresController.find({ user: { role: UserRole.admin } }, '6093ba0e2ab5775cfc01ed33'); expect(response).toBeTruthy(); expect((await response).deletedAt).toBeTruthy(); }); it('should not find deleted structure as anonymous', async () => { try { - await controller.find({ user: {} }, '6093ba0e2ab5775cfc01ed33'); + await structuresController.find({ user: {} }, '6093ba0e2ab5775cfc01ed33'); expect(true).toBe(false); } catch (error) { expect(error.status).toEqual(HttpStatus.NOT_FOUND); @@ -208,35 +209,35 @@ describe('StructuresController', () => { }); it('should find struct with owners', async () => { - const res = controller.findWithOwners('6093ba0e2ab5775cfc01ed3e'); + const res = structuresController.findWithOwners('6093ba0e2ab5775cfc01ed3e'); expect(res).toBeTruthy(); }); it('should delete struct', async () => { const req = { user: { _id: '6036721022462b001334c4bb' } }; - const res = controller.delete(req, '6093ba0e2ab5775cfc01ed3e'); + const res = structuresController.delete(req, '6093ba0e2ab5775cfc01ed3e'); expect(res).toBeTruthy(); }); it('should cancel struct delete', async () => { const req = { user: { _id: '6036721022462b001334c4bb' } }; - const res = controller.cancelDelete(req, '6093ba0e2ab5775cfc01ed3e'); + const res = structuresController.cancelDelete(req, '6093ba0e2ab5775cfc01ed3e'); expect(res).toBeTruthy(); }); it('should add Owner', async () => { - let res = controller.addOwner('6093ba0e2ab5775cfc01ed3e', { email: 'pauline.dupont@mii.com' }); + let res = structuresController.addOwner('6093ba0e2ab5775cfc01ed3e', { email: 'pauline.dupont@mii.com' }); expect(res).toBeTruthy(); - res = controller.addOwner('6093ba0e2ab5775cfc01ed3e', { email: 'pauline.dupont@mii.fr' }); + res = structuresController.addOwner('6093ba0e2ab5775cfc01ed3e', { email: 'pauline.dupont@mii.fr' }); expect(res).toBeTruthy(); - res = controller.addOwner('', { email: 'pauline.dupont@mii.fr' }); + res = structuresController.addOwner('', { email: 'pauline.dupont@mii.fr' }); expect(res).toBeTruthy(); }); describe('removeOwner', () => { it('should return invalid structure', async () => { try { - await controller.removeOwner('invalidstructure', '63639058685ba134c32bc495'); + await structuresController.removeOwner('invalidstructure', '63639058685ba134c32bc495'); expect(true).toBe(false); } catch (e) { expect(e.message).toEqual('Invalid Structure'); @@ -245,7 +246,7 @@ describe('StructuresController', () => { }); it('should return invalid user', async () => { try { - await controller.removeOwner('6093ba0e2ab5775cfc01ed3e', 'invaliduser'); + await structuresController.removeOwner('6093ba0e2ab5775cfc01ed3e', 'invaliduser'); expect(true).toBe(false); } catch (e) { expect(e.message).toEqual('Invalid User'); @@ -256,7 +257,7 @@ describe('StructuresController', () => { jest.spyOn(usersService, 'getPersonalOfferInStructure').mockImplementationOnce(() => null); const removeFromStructureLinkedSpyer = jest.spyOn(usersService, 'removeFromStructureLinked'); const deleteOfferSpyer = jest.spyOn(personalOffersService, 'delete'); - await controller.removeOwner('6093ba0e2ab5775cfc01ed3e', '63639058685ba134c32bc495'); + await structuresController.removeOwner('6093ba0e2ab5775cfc01ed3e', '63639058685ba134c32bc495'); expect(removeFromStructureLinkedSpyer).toBeCalledTimes(1); expect(deleteOfferSpyer).toBeCalledTimes(0); }); @@ -275,24 +276,24 @@ describe('StructuresController', () => { jest.spyOn(usersService, 'getPersonalOfferInStructure').mockImplementationOnce(() => result); const removeFromStructureLinkedSpyer = jest.spyOn(usersService, 'removeFromStructureLinked'); const deleteOfferSpyer = jest.spyOn(personalOffersService, 'delete'); - await controller.removeOwner('6093ba0e2ab5775cfc01ed3e', '63639058685ba134c32bc495'); + await structuresController.removeOwner('6093ba0e2ab5775cfc01ed3e', '63639058685ba134c32bc495'); expect(removeFromStructureLinkedSpyer).toBeCalledTimes(1); expect(deleteOfferSpyer).toBeCalledTimes(1); }); }); it('should remove temp user', async () => { - const res = controller.removeTempUser('6093ba0e2ab5775cfc01ed3e', 'tsfsf6296'); + const res = structuresController.removeTempUser('6093ba0e2ab5775cfc01ed3e', 'tsfsf6296'); expect(res).toBeTruthy(); }); it('should remove user from struct', async () => { - const res = controller.removeOwner('6093ba0e2ab5775cfc01ed3e', 'tsfsf6296'); + const res = structuresController.removeOwner('6093ba0e2ab5775cfc01ed3e', 'tsfsf6296'); expect(res).toBeTruthy(); }); it('should report any structure error', async () => { - const res = controller.reportStructureError({ structureId: '6093ba0e2ab5775cfc01ed3e', content: null }); + const res = structuresController.reportStructureError({ structureId: '6093ba0e2ab5775cfc01ed3e', content: null }); expect(res).toBeTruthy(); }); }); diff --git a/src/temp-user/temp-user.controller.spec.ts b/src/temp-user/temp-user.controller.spec.ts index ca61b3452d6b7671cce3c78412ec851d9c9eb24b..5bd3e66888865875e086fc36c376f02de54a5eed 100644 --- a/src/temp-user/temp-user.controller.spec.ts +++ b/src/temp-user/temp-user.controller.spec.ts @@ -6,7 +6,7 @@ import { TempUserController } from './temp-user.controller'; import { TempUserService } from './temp-user.service'; describe('TempUserService', () => { - let controller: TempUserController; + let tempUserController: TempUserController; const mockTempUserService = { findById: jest.fn(), @@ -19,24 +19,24 @@ describe('TempUserService', () => { controllers: [TempUserController], }).compile(); - controller = module.get<TempUserController>(TempUserController); + tempUserController = module.get<TempUserController>(TempUserController); }); it('should be defined', () => { - expect(controller).toBeDefined(); + expect(tempUserController).toBeDefined(); }); describe('getTempUser', () => { it('should get temporary users', async () => { const tmpUser = { email: 'test@test.com', pendingStructuresLink: [] }; mockTempUserService.findById.mockReturnValueOnce(tmpUser); - expect(await controller.getTempUser('addq651')).toEqual(tmpUser); + expect(await tempUserController.getTempUser('addq651')).toEqual(tmpUser); }); it('should throw error in cas of no users', async () => { const tmpUser = null; mockTempUserService.findById.mockReturnValueOnce(tmpUser); try { - await controller.getTempUser('addq651'); + await tempUserController.getTempUser('addq651'); // Fail test if above expression doesn't throw anything. expect(true).toBe(false); } catch (e) { diff --git a/src/temp-user/temp-user.service.spec.ts b/src/temp-user/temp-user.service.spec.ts index 458b7c32fcf911d9c2aeea16d56c82dd016ad16b..6eecac7886b16444cd363ee023156c5bf5a93095 100644 --- a/src/temp-user/temp-user.service.spec.ts +++ b/src/temp-user/temp-user.service.spec.ts @@ -6,7 +6,7 @@ import { MailerModule } from '../mailer/mailer.module'; import { TempUserService } from './temp-user.service'; describe('TempUserService', () => { - let service: TempUserService; + let tempUserService: TempUserService; const tempUserModelMock = { create: jest.fn(), @@ -31,11 +31,11 @@ describe('TempUserService', () => { ], }).compile(); - service = module.get<TempUserService>(TempUserService); + tempUserService = module.get<TempUserService>(TempUserService); }); it('should be defined', () => { - expect(service).toBeDefined(); + expect(tempUserService).toBeDefined(); }); describe('create', () => { const tmpUser = { email: 'test@test.com', pendingStructuresLink: [] }; @@ -43,7 +43,7 @@ describe('TempUserService', () => { tempUserModelMock.findOne.mockReturnThis(); tempUserModelMock.exec.mockResolvedValueOnce(tmpUser); try { - await service.create(tmpUser, 'PIMMS Framboise'); + await tempUserService.create(tmpUser, 'PIMMS Framboise'); expect(true).toBe(false); } catch (e) { expect(e.message).toEqual('User already exists'); @@ -54,21 +54,21 @@ describe('TempUserService', () => { tempUserModelMock.findOne.mockReturnThis(); tempUserModelMock.exec.mockResolvedValueOnce(null).mockResolvedValueOnce(tmpUser); tempUserModelMock.create.mockResolvedValueOnce(tmpUser); - expect(await service.create(tmpUser, 'PIMMS Framboise')).toEqual(tmpUser); + expect(await tempUserService.create(tmpUser, 'PIMMS Framboise')).toEqual(tmpUser); }); }); it('should find one', async () => { const tmpUser = { email: 'test2@test.com', pendingStructuresLink: [] }; tempUserModelMock.findOne.mockReturnThis(); tempUserModelMock.exec.mockResolvedValueOnce(tmpUser); - expect(await service.findOne('test2@test.com')).toEqual(tmpUser); + expect(await tempUserService.findOne('test2@test.com')).toEqual(tmpUser); }); it('should find one by id', async () => { const tmpUser = { email: 'test2@test.com', pendingStructuresLink: [] }; tempUserModelMock.findById.mockReturnThis(); tempUserModelMock.exec.mockResolvedValueOnce(tmpUser); - expect(await service.findById('5fbb92e480a5c257dc0161f0')).toEqual(tmpUser); + expect(await tempUserService.findById('5fbb92e480a5c257dc0161f0')).toEqual(tmpUser); }); describe('delete', () => { @@ -78,13 +78,13 @@ describe('TempUserService', () => { tempUserModelMock.exec.mockResolvedValueOnce(tmpUser); tempUserModelMock.deleteOne.mockReturnThis(); tempUserModelMock.exec.mockImplementationOnce(() => ({})); - expect(await service.delete('toto@test.com')).toEqual(tmpUser); + expect(await tempUserService.delete('toto@test.com')).toEqual(tmpUser); }); it('should return an error : user does not exist', async () => { tempUserModelMock.findOne.mockReturnThis(); tempUserModelMock.exec.mockResolvedValueOnce(null); try { - await service.delete('toto@test.com'); + await tempUserService.delete('toto@test.com'); expect(true).toBe(false); } catch (e) { expect(e.message).toEqual('User does not exists'); @@ -99,7 +99,7 @@ describe('TempUserService', () => { tempUserModelMock.find.mockReturnThis(); tempUserModelMock.exec.mockResolvedValueOnce([]).mockResolvedValueOnce(tmpUser); tempUserModelMock.findByIdAndUpdate.mockReturnThis(); - expect(await service.updateStructureLinked(tmpUser)).toEqual(tmpUser); + expect(await tempUserService.updateStructureLinked(tmpUser)).toEqual(tmpUser); }); it('should not update structure linked: User already linked', async () => { const tmpUser = { email: 'test2@test.com', structuresLink: [] }; @@ -107,7 +107,7 @@ describe('TempUserService', () => { tempUserModelMock.findByIdAndUpdate.mockReturnThis(); tempUserModelMock.exec.mockResolvedValueOnce([tmpUser]); try { - await service.updateStructureLinked(tmpUser); + await tempUserService.updateStructureLinked(tmpUser); } catch (e) { expect(e.message).toEqual('User already linked'); expect(e.status).toEqual(HttpStatus.UNPROCESSABLE_ENTITY); diff --git a/src/users/controllers/employer.controller.spec.ts b/src/users/controllers/employer.controller.spec.ts index 1eb82a3e9413b38a69a9949717640bd03744a271..d39b9f57002b96b422464dc55d7bfeffbee854a2 100644 --- a/src/users/controllers/employer.controller.spec.ts +++ b/src/users/controllers/employer.controller.spec.ts @@ -11,7 +11,7 @@ import { UsersService } from '../services/users.service'; import { EmployerController } from './employer.controller'; describe('EmployerController', () => { - let controller: EmployerController; + let employerController: EmployerController; let userService: UsersService; const employerServiceMock = { @@ -51,12 +51,12 @@ describe('EmployerController', () => { controllers: [EmployerController], }).compile(); - controller = module.get<EmployerController>(EmployerController); + employerController = module.get<EmployerController>(EmployerController); userService = module.get<UsersService>(UsersService); }); it('should be defined', () => { - expect(controller).toBeDefined(); + expect(employerController).toBeDefined(); }); describe('findAll', () => { @@ -73,7 +73,7 @@ describe('EmployerController', () => { validated: true, }, ]); - const findAllReply = await controller.findAll(); + const findAllReply = await employerController.findAll(); expect(findAllReply.length).toBe(2); }); it('should return searched elements with query `CA`', async () => { @@ -89,7 +89,7 @@ describe('EmployerController', () => { validated: true, }, ]); - const findAllReply = await controller.findAll({ search: 'CA' }); + const findAllReply = await employerController.findAll({ search: 'CA' }); expect(findAllReply.length).toBe(2); }); }); @@ -142,7 +142,7 @@ describe('EmployerController', () => { validated: true, }, ]); - const index = await controller.resetES(); + const index = await employerController.resetES(); expect(index.length).toBe(2); }); }); @@ -156,7 +156,7 @@ describe('EmployerController', () => { validated: true, }); const req = { user: { _id: '6036721022462b001334c4bb', role: 0 } }; - const reply = await controller.createEmployer({ name: 'Sopra' }, req); + const reply = await employerController.createEmployer({ name: 'Sopra' }, req); expect(reply).toBeTruthy(); }); it('should not create if employer already exists', async () => { @@ -167,7 +167,7 @@ describe('EmployerController', () => { }); const req = { user: { _id: '6036721022462b001334c4bb' }, role: 0 }; try { - await controller.createEmployer({ name: 'Sopra' }, req); + await employerController.createEmployer({ name: 'Sopra' }, req); expect; } catch (e) { expect(e.message).toBe('Employer already exist'); @@ -182,7 +182,7 @@ describe('EmployerController', () => { employerServiceMock.create.mockResolvedValueOnce({ ...employer, validated: true }); const req = { user: { _id: '6036721022462b001334c4bb', role: 1 } }; - const reply = await controller.createEmployer(employer, req); + const reply = await employerController.createEmployer(employer, req); expect(reply).toBeTruthy(); expect(employerServiceMock.create).toHaveBeenCalledWith(employer, true, false); }); @@ -194,7 +194,7 @@ describe('EmployerController', () => { name: 'Sopra', validated: true, }); - expect(await controller.validateEmployer({ id: '6231aefe76598527c8d0b5bc' })).toBeTruthy(); + expect(await employerController.validateEmployer({ id: '6231aefe76598527c8d0b5bc' })).toBeTruthy(); }); }); describe('Get Employers', () => { @@ -212,7 +212,7 @@ describe('EmployerController', () => { validated: true, }, ]); - await controller.findValidatedEmployers(); + await employerController.findValidatedEmployers(); expect(employerServiceMock.findAllValidated.mock.calls.length).toBe(1); expect(spyer.mock.calls.length).toBe(1); }); @@ -231,7 +231,7 @@ describe('EmployerController', () => { validated: false, }, ]); - await controller.findUnvalidatedEmployers(); + await employerController.findUnvalidatedEmployers(); expect(employerServiceMock.findAllUnvalidated.mock.calls.length).toBe(1); expect(spyer.mock.calls.length).toBe(1); }); @@ -243,7 +243,7 @@ describe('EmployerController', () => { name: 'SopraMod', validated: true, }); - expect(await controller.updateEmployer('6231aefe76598527c8d0b5bc', { name: 'SopraMod' })).toBeTruthy(); + expect(await employerController.updateEmployer('6231aefe76598527c8d0b5bc', { name: 'SopraMod' })).toBeTruthy(); }); it('should delete an unvalidated employer and replace all its occurence with a chosen validated employer', async () => { @@ -258,7 +258,7 @@ describe('EmployerController', () => { deletedCount: 1, }); - const reply = await controller.mergeEmployer({ + const reply = await employerController.mergeEmployer({ sourceEmployerId: '6231aefe76598527c8d0b5ba', targetEmployerId: '6231aefe76598527c8d0b5bc', }); @@ -278,7 +278,7 @@ describe('EmployerController', () => { name: 'Sopra', validated: true, }); - const reply = await controller.deleteEmployer({ id: '6231aefe76598527c8d0b5ba' }); + const reply = await employerController.deleteEmployer({ id: '6231aefe76598527c8d0b5ba' }); expect(reply).toBeTruthy(); }); @@ -289,7 +289,7 @@ describe('EmployerController', () => { validated: true, }); try { - await controller.deleteEmployer({ id: '6231aefe76598527c8d0b5bc' }); + await employerController.deleteEmployer({ id: '6231aefe76598527c8d0b5bc' }); expect(true).toBe(false); } catch (e) { expect(e.message).toEqual('Cannot delete employer. It has user(s) attached to it.'); diff --git a/src/users/controllers/jobs.controller.spec.ts b/src/users/controllers/jobs.controller.spec.ts index 89a11ad7fd9a96142cd6b652c1475408c8887603..28c9386d5d92fe85f654fb4e40ae09d5362df790 100644 --- a/src/users/controllers/jobs.controller.spec.ts +++ b/src/users/controllers/jobs.controller.spec.ts @@ -12,7 +12,7 @@ import { UsersService } from '../services/users.service'; import { JobsController } from './jobs.controller'; describe('JobsController', () => { - let controller: JobsController; + let jobsController: JobsController; const jobServiceMock = { findAll: jest.fn(), @@ -57,11 +57,11 @@ describe('JobsController', () => { controllers: [JobsController], }).compile(); - controller = module.get<JobsController>(JobsController); + jobsController = module.get<JobsController>(JobsController); }); it('should be defined', () => { - expect(controller).toBeDefined(); + expect(jobsController).toBeDefined(); }); describe('findAll', () => { @@ -82,7 +82,7 @@ describe('JobsController', () => { jobsGroup: null, }, ]); - const reply = await controller.findAll(); + const reply = await jobsController.findAll(); expect(reply.length).toBe(2); }); }); @@ -103,7 +103,7 @@ describe('JobsController', () => { jobServiceMock.findByName.mockResolvedValueOnce(null); jobServiceMock.create.mockResolvedValueOnce(newCreatedJob); const req = { user: { _id: '6036721022462b001334c4bb' } }; - const createReply = await controller.createJob(req, newJob); + const createReply = await jobsController.createJob(req, newJob); expect(createReply).toEqual(newCreatedJob); }); it('should throw error on already existing job `Dev`', async () => { @@ -121,7 +121,7 @@ describe('JobsController', () => { }); try { const req = { user: { _id: '6036721022462b001334c4bb' } }; - await controller.createJob(req, newJob); + await jobsController.createJob(req, newJob); expect(true).toBe(false); } catch (e) { expect(e.message).toBe('Job already exist'); @@ -139,7 +139,7 @@ describe('JobsController', () => { validated: true, }); const req = { user: { _id: '6036721022462b001334c4bb', role: 0 } }; - const reply = await controller.createJob(req, { name: 'Dev', hasPersonalOffer: true, jobsGroup: null }); + const reply = await jobsController.createJob(req, { name: 'Dev', hasPersonalOffer: true, jobsGroup: null }); expect(reply).toBeTruthy(); }); it('should not create if job already exists', async () => { @@ -150,7 +150,7 @@ describe('JobsController', () => { }); const req = { user: { _id: '6036721022462b001334c4bb', role: 0 } }; try { - await controller.createJob(req, { name: 'Dev', hasPersonalOffer: true, jobsGroup: null }); + await jobsController.createJob(req, { name: 'Dev', hasPersonalOffer: true, jobsGroup: null }); } catch (e) { expect(e.message).toBe('Job already exist'); expect(e.status).toBe(HttpStatus.UNPROCESSABLE_ENTITY); @@ -165,7 +165,7 @@ describe('JobsController', () => { }); const req = { user: { _id: '6036721022462b001334c4bb', role: 1 } }; const job = { name: 'Dev', hasPersonalOffer: true, jobsGroup: null }; - const reply = await controller.createJob(req, job); + const reply = await jobsController.createJob(req, job); expect(reply).toBeTruthy(); expect(jobServiceMock.create).toHaveBeenCalledWith(job, true, true, false); }); @@ -177,7 +177,7 @@ describe('JobsController', () => { name: 'Dev', validated: true, }); - expect(await controller.validateJob({ id: '6231aefe76598527c8d0b5bc' })).toBeTruthy(); + expect(await jobsController.validateJob({ id: '6231aefe76598527c8d0b5bc' })).toBeTruthy(); }); }); describe('Get Jobs', () => { @@ -195,7 +195,7 @@ describe('JobsController', () => { validated: true, }, ]); - await controller.findValidatedJobs(); + await jobsController.findValidatedJobs(); expect(jobServiceMock.findAll.mock.calls.length).toBe(2); expect(spyer.mock.calls.length).toBe(1); }); @@ -214,7 +214,7 @@ describe('JobsController', () => { validated: false, }, ]); - await controller.findUnvalidatedJobs(); + await jobsController.findUnvalidatedJobs(); expect(jobServiceMock.findAllUnvalidated.mock.calls.length).toBe(1); expect(spyer.mock.calls.length).toBe(2); }); @@ -227,7 +227,7 @@ describe('JobsController', () => { validated: true, }); expect( - await controller.updateJob('6231aefe76598527c8d0b5bc', { + await jobsController.updateJob('6231aefe76598527c8d0b5bc', { name: 'DevMod', hasPersonalOffer: false, jobsGroup: null, @@ -247,7 +247,7 @@ describe('JobsController', () => { deletedCount: 1, }); - const reply = await controller.mergeJob({ + const reply = await jobsController.mergeJob({ sourceJobId: '6231aefe76598527c8d0b5ba', targetJobId: '6231aefe76598527c8d0b5bc', }); @@ -268,7 +268,7 @@ describe('JobsController', () => { validated: true, }); userServiceMock.isJobLinkedtoUser.mockResolvedValueOnce(false); - const reply = await controller.deleteJob({ id: '6231aefe76598527c8d0b5ba' }); + const reply = await jobsController.deleteJob({ id: '6231aefe76598527c8d0b5ba' }); expect(reply).toBeTruthy(); }); @@ -280,7 +280,7 @@ describe('JobsController', () => { }); userServiceMock.isJobLinkedtoUser.mockResolvedValueOnce(true); try { - await controller.deleteJob({ id: '6231aefe76598527c8d0b5bc' }); + await jobsController.deleteJob({ id: '6231aefe76598527c8d0b5bc' }); expect(true).toBe(false); } catch (e) { expect(e.message).toEqual('Cannot delete job. It has user(s) attached to it.'); diff --git a/src/users/controllers/jobsGroups.controller.spec.ts b/src/users/controllers/jobsGroups.controller.spec.ts index f2a2a160bdf4db81ed040ca2573972015b0d4a23..66e89371235a9fc51b1efd440205e192f9556695 100644 --- a/src/users/controllers/jobsGroups.controller.spec.ts +++ b/src/users/controllers/jobsGroups.controller.spec.ts @@ -6,12 +6,12 @@ import { Types } from 'mongoose'; import { ConfigurationModule } from '../../configuration/configuration.module'; import { CreateJobsGroupsDto } from '../dto/create-jobsGroups.dto'; import { JobsGroups } from '../schemas/jobsGroups.schema'; +import { JobsService } from '../services/jobs.service'; import { JobsGroupsService } from '../services/jobsGroups.service'; import { JobsGroupsController } from './jobsGroups.controller'; -import { JobsService } from '../services/jobs.service'; describe('JobsGroupsController', () => { - let controller: JobsGroupsController; + let jobsGroupsController: JobsGroupsController; const jobsGroupsServiceMock = { findAll: jest.fn(), @@ -47,11 +47,11 @@ describe('JobsGroupsController', () => { controllers: [JobsGroupsController], }).compile(); - controller = module.get<JobsGroupsController>(JobsGroupsController); + jobsGroupsController = module.get<JobsGroupsController>(JobsGroupsController); }); it('should be defined', () => { - expect(controller).toBeDefined(); + expect(jobsGroupsController).toBeDefined(); }); describe('findAll', () => { @@ -66,7 +66,7 @@ describe('JobsGroupsController', () => { name: 'Coordination', }, ]); - const reply = await controller.findAll(); + const reply = await jobsGroupsController.findAll(); expect(reply.length).toBe(2); }); }); @@ -81,7 +81,7 @@ describe('JobsGroupsController', () => { }; jobsGroupsServiceMock.findByName.mockResolvedValueOnce(null); jobsGroupsServiceMock.create.mockResolvedValueOnce(newCreatedJobsGroups); - const createReply = await controller.createJobsGroups(newJobsGroups); + const createReply = await jobsGroupsController.createJobsGroups(newJobsGroups); expect(createReply).toEqual(newCreatedJobsGroups); }); it('should throw error on already existing job group `Dev`', async () => { @@ -93,7 +93,7 @@ describe('JobsGroupsController', () => { name: 'Dev', }); try { - await controller.createJobsGroups(newJobsGroups); + await jobsGroupsController.createJobsGroups(newJobsGroups); expect(true).toBe(false); } catch (e) { expect(e.message).toBe('Job group already exist'); @@ -108,7 +108,7 @@ describe('JobsGroupsController', () => { _id: new Types.ObjectId('6231aefe76598527c8d0b5bc'), name: 'DevMod', }); - expect(await controller.updateJobsGroups('6231aefe76598527c8d0b5bc', { name: 'DevMod' })).toBeTruthy(); + expect(await jobsGroupsController.updateJobsGroups('6231aefe76598527c8d0b5bc', { name: 'DevMod' })).toBeTruthy(); }); }); describe('Delete Job Group', () => { @@ -124,7 +124,7 @@ describe('JobsGroupsController', () => { name: 'Dev', }); jobServiceMock.getJobsGroupsAttachedJobs.mockResolvedValueOnce([]); - const reply = await controller.deleteJobsGroups({ id: '6231aefe76598527c8d0b5ba' }); + const reply = await jobsGroupsController.deleteJobsGroups({ id: '6231aefe76598527c8d0b5ba' }); expect(reply).toBeTruthy(); }); @@ -135,7 +135,7 @@ describe('JobsGroupsController', () => { }); jobServiceMock.getJobsGroupsAttachedJobs.mockResolvedValueOnce([{ test: 1 }]); try { - await controller.deleteJobsGroups({ id: '6231aefe76598527c8d0b5bc' }); + await jobsGroupsController.deleteJobsGroups({ id: '6231aefe76598527c8d0b5bc' }); expect(true).toBe(false); } catch (e) { expect(e.message).toEqual('Cannot delete job group. It has job(s) attached to it.'); diff --git a/src/users/controllers/userRegistry.controller.spec.ts b/src/users/controllers/userRegistry.controller.spec.ts index 115ed62a4e36ace249e61b185e4700a230384c26..64a6db269738868c0e04ce7e16c2eff0b111df51 100644 --- a/src/users/controllers/userRegistry.controller.spec.ts +++ b/src/users/controllers/userRegistry.controller.spec.ts @@ -11,7 +11,7 @@ import { UserRegistryService } from '../services/userRegistry.service'; import { UsersRegistryController } from './userRegistry.controller'; describe('UserRegistryController', () => { - let controller: UsersRegistryController; + let userRegistryController: UsersRegistryController; const userRegistryServiceMock = { findAllForIndexation: jest.fn(), @@ -44,17 +44,17 @@ describe('UserRegistryController', () => { .useValue(mockRoleGuard) .compile(); - controller = module.get<UsersRegistryController>(UsersRegistryController); + userRegistryController = module.get<UsersRegistryController>(UsersRegistryController); }); it('should be defined', () => { - expect(controller).toBeDefined(); + expect(userRegistryController).toBeDefined(); }); describe('findAll', () => { it('should findAll with searchTerm, job and employer', async () => { userRegistryServiceMock.findUsersByNameEmployerOrJobsGroup.mockResolvedValue([multipleUsers[0]]); - const reply = await controller.findAll( + const reply = await userRegistryController.findAll( { search: 'adm' }, { page: 1, jobsGroup: ['Technique'], employer: ['Pimms'] } ); @@ -62,66 +62,69 @@ describe('UserRegistryController', () => { }); it('should findAll with searchTerm, empty job and empty employer', async () => { userRegistryServiceMock.findUsersByNameEmployerOrJobsGroup.mockResolvedValue([multipleUsers[0]]); - const reply = await controller.findAll({ search: 'adm' }, { page: 1, jobsGroup: [], employer: [] }); + const reply = await userRegistryController.findAll({ search: 'adm' }, { page: 1, jobsGroup: [], employer: [] }); expect(reply).toStrictEqual([multipleUsers[0]]); }); it('should findAll with searchTerm and no filter arrays', async () => { userRegistryServiceMock.findUsersByNameEmployerOrJobsGroup.mockResolvedValue([multipleUsers[0]]); - const reply = await controller.findAll({ search: 'adm' }, { page: 1 }); + const reply = await userRegistryController.findAll({ search: 'adm' }, { page: 1 }); expect(reply).toStrictEqual([multipleUsers[0]]); }); it('should findAll with searchTerm and empty job', async () => { userRegistryServiceMock.findUsersByNameEmployerOrJobsGroup.mockResolvedValue([multipleUsers[0]]); - const reply = await controller.findAll({ search: 'adm' }, { page: 1, jobsGroup: [] }); + const reply = await userRegistryController.findAll({ search: 'adm' }, { page: 1, jobsGroup: [] }); expect(reply).toStrictEqual([multipleUsers[0]]); }); it('should findAll with searchTerm and empty employer', async () => { userRegistryServiceMock.findUsersByNameEmployerOrJobsGroup.mockResolvedValue([multipleUsers[0]]); - const reply = await controller.findAll({ search: 'adm' }, { page: 1, employer: [] }); + const reply = await userRegistryController.findAll({ search: 'adm' }, { page: 1, employer: [] }); expect(reply).toStrictEqual([multipleUsers[0]]); }); it('should findAll with no searchTerm and employer filter', async () => { userRegistryServiceMock.findUsersByNameEmployerOrJobsGroup.mockResolvedValue([multipleUsers[0]]); - const reply = await controller.findAll({ search: '' }, { page: 1, employer: ['CAF'] }); + const reply = await userRegistryController.findAll({ search: '' }, { page: 1, employer: ['CAF'] }); expect(reply).toStrictEqual([multipleUsers[0]]); }); it('should findAll with no searchTerm and job filter', async () => { userRegistryServiceMock.findUsersByNameEmployerOrJobsGroup.mockResolvedValue([multipleUsers[0]]); - const reply = await controller.findAll({ search: '' }, { page: 1, jobsGroup: ['Technique'] }); + const reply = await userRegistryController.findAll({ search: '' }, { page: 1, jobsGroup: ['Technique'] }); expect(reply).toStrictEqual([multipleUsers[0]]); }); it('should findAll with no searchTerm and filters', async () => { userRegistryServiceMock.findUsersByNameEmployerOrJobsGroup.mockResolvedValue([multipleUsers[0]]); - const reply = await controller.findAll({ search: '' }, { page: 1, jobsGroup: ['Technique'], employer: ['CAF'] }); + const reply = await userRegistryController.findAll( + { search: '' }, + { page: 1, jobsGroup: ['Technique'], employer: ['CAF'] } + ); expect(reply).toStrictEqual([multipleUsers[0]]); }); it('should findAll with searchTerm and undefined filters', async () => { userRegistryServiceMock.findUsersByNameEmployerOrJobsGroup.mockResolvedValue([multipleUsers[0]]); - const reply = await controller.findAll({ search: 'adm' }); + const reply = await userRegistryController.findAll({ search: 'adm' }); expect(reply).toStrictEqual([multipleUsers[0]]); }); it('should findAll with no searchTerm and no filter arrays', async () => { userRegistryServiceMock.findAllUserRegistry.mockResolvedValue(multipleUsers); - const reply = await controller.findAll({ search: '' }, { page: 1 }); + const reply = await userRegistryController.findAll({ search: '' }, { page: 1 }); expect(reply).toBe(multipleUsers); }); it('should findAll with empty search end undefined filters', async () => { userRegistryServiceMock.findAllUserRegistry.mockResolvedValue(multipleUsers); - const reply = await controller.findAll({ search: '' }); + const reply = await userRegistryController.findAll({ search: '' }); expect(reply).toBe(multipleUsers); }); }); describe('findAllCount', () => { it('should findAllCount', async () => { userRegistryServiceMock.countAllUserRegistry.mockResolvedValue(10); - const reply = await controller.findAllCount(); + const reply = await userRegistryController.findAllCount(); expect(reply).toStrictEqual(10); }); }); describe('resetES', () => { it('should reset elastic search indexes', async () => { userRegistryServiceMock.initUserRegistryIndex.mockResolvedValue(multipleUsers); - const reply = await controller.resetES(); + const reply = await userRegistryController.resetES(); expect(reply).toStrictEqual(multipleUsers); }); }); diff --git a/src/users/controllers/users.controller.spec.ts b/src/users/controllers/users.controller.spec.ts index 6760594ee110717b2df4a5786829109fbeb1cda7..43739c000b54df25a50babf29be9d3d8107a7aae 100644 --- a/src/users/controllers/users.controller.spec.ts +++ b/src/users/controllers/users.controller.spec.ts @@ -30,7 +30,7 @@ import { PasswordResetDto } from './../dto/reset-password.dto'; import { UsersController } from './users.controller'; describe('UsersController', () => { - let controller: UsersController; + let usersController: UsersController; const employerServiceMock = { findByName: jest.fn(), @@ -127,19 +127,19 @@ describe('UsersController', () => { controllers: [UsersController], }).compile(); - controller = module.get<UsersController>(UsersController); + usersController = module.get<UsersController>(UsersController); }); afterEach(() => { jest.clearAllMocks(); }); it('should be defined', () => { - expect(controller).toBeDefined(); + expect(usersController).toBeDefined(); }); describe('getProfile', () => { it('should return user', () => { const user = { _id: '36', email: 'a@a.com' }; - const result = controller.getProfile({ user: user }); + const result = usersController.getProfile({ user: user }); expect(result).toEqual(user); }); }); @@ -152,7 +152,7 @@ describe('UsersController', () => { }; employerServiceMock.findByName.mockResolvedValueOnce(null); try { - await controller.setProfile({ user: { _id: '36', email: 'a@a.com' } }, profile); + await usersController.setProfile({ user: { _id: '36', email: 'a@a.com' } }, profile); expect(true).toBe(false); } catch (e) { expect(e.message).toBe('Employer does not exist'); @@ -171,7 +171,7 @@ describe('UsersController', () => { }); jobServiceMock.findByName.mockResolvedValue(null); try { - await controller.setProfile({ user: { _id: '36', email: 'a@a.com' } }, profile); + await usersController.setProfile({ user: { _id: '36', email: 'a@a.com' } }, profile); expect(true).toBe(false); } catch (e) { expect(e.message).toBe('Job does not exist'); @@ -214,7 +214,7 @@ describe('UsersController', () => { employer: new Types.ObjectId('6231aefe76598527c8d0b5a7'), job: new Types.ObjectId('6231aefe76598527c8d0b5be'), }); - const reply = await controller.setProfile({ user: { _id: '36', email: 'a@a.com' } }, profile); + const reply = await usersController.setProfile({ user: { _id: '36', email: 'a@a.com' } }, profile); expect(reply).toBeTruthy(); }); }); @@ -246,7 +246,7 @@ describe('UsersController', () => { employer: new Types.ObjectId('6231aefe76598527c8d0b5a7'), job: new Types.ObjectId('6231aefe76598527c8d0b5be'), }); - const reply = await controller.updateDetails({ user: { _id: '36', email: 'a@a.com' } }, newDetails); + const reply = await usersController.updateDetails({ user: { _id: '36', email: 'a@a.com' } }, newDetails); expect(reply).toBeTruthy(); }); }); @@ -262,7 +262,7 @@ describe('UsersController', () => { const createUserDto = new CreateUserDto(); userServiceMock.create.mockResolvedValueOnce(usersMockData[0]); - const result = await controller.create(createUserDto); + const result = await usersController.create(createUserDto); expect(userCreateSpyer).toBeCalledTimes(1); expect(structureFindOneSpyer).toBeCalledTimes(0); @@ -284,7 +284,7 @@ describe('UsersController', () => { const createUserDto = new CreateUserDto(); userServiceMock.create.mockResolvedValueOnce(usersMockData[0]); tempUserServiceMock.findOne.mockResolvedValueOnce({ email: 'test@test.com', pendingStructuresLink: [] }); - const result = await controller.create(createUserDto); + const result = await usersController.create(createUserDto); expect(userCreateSpyer).toBeCalledTimes(1); expect(structureFindOneSpyer).toBeCalledTimes(0); @@ -299,7 +299,7 @@ describe('UsersController', () => { describe('validateUser', () => { it('should call validateUser', async () => { const spyer = jest.spyOn(userServiceMock, 'validateUser'); - await controller.validateUser({ id: 1 }, 'token'); + await usersController.validateUser({ id: 1 }, 'token'); expect(spyer).toBeCalledTimes(1); }); }); @@ -307,7 +307,7 @@ describe('UsersController', () => { describe('changePassword', () => { it('should call changeUserPassword', async () => { const spyer = jest.spyOn(userServiceMock, 'changeUserPassword'); - await controller.changePassword({ user: { _id: '36', email: 'a@a.com' } }, new PasswordChangeDto()); + await usersController.changePassword({ user: { _id: '36', email: 'a@a.com' } }, new PasswordChangeDto()); expect(spyer).toBeCalledTimes(1); }); }); @@ -315,7 +315,7 @@ describe('UsersController', () => { describe('changeEmail', () => { it('should call changeUserEmail', async () => { const spyer = jest.spyOn(userServiceMock, 'changeUserEmail'); - await controller.changeEmail(new EmailChangeDto()); + await usersController.changeEmail(new EmailChangeDto()); expect(spyer).toBeCalledTimes(1); }); }); @@ -323,7 +323,7 @@ describe('UsersController', () => { describe('verifyAndUpdateEmail', () => { it('should call verifyAndUpdateUserEmail', async () => { const spyer = jest.spyOn(userServiceMock, 'verifyAndUpdateUserEmail'); - await controller.verifyAndUpdateEmail('token'); + await usersController.verifyAndUpdateEmail('token'); expect(spyer).toBeCalledTimes(1); }); }); @@ -331,7 +331,7 @@ describe('UsersController', () => { describe('resetPassword', () => { it('should call sendResetPasswordEmail', async () => { const spyer = jest.spyOn(userServiceMock, 'sendResetPasswordEmail'); - await controller.resetPassword(new PasswordResetDto()); + await usersController.resetPassword(new PasswordResetDto()); expect(spyer).toBeCalledTimes(1); }); }); @@ -339,7 +339,7 @@ describe('UsersController', () => { describe('resetPasswordApply', () => { it('should call validatePasswordResetToken', async () => { const spyer = jest.spyOn(userServiceMock, 'validatePasswordResetToken'); - await controller.resetPasswordApply(new PasswordResetApplyDto()); + await usersController.resetPasswordApply(new PasswordResetApplyDto()); expect(spyer).toBeCalledTimes(1); }); }); @@ -347,7 +347,7 @@ describe('UsersController', () => { describe('verifyUserExist', () => { it('should call verifyUserExist', async () => { const spyer = jest.spyOn(userServiceMock, 'verifyUserExist'); - await controller.verifyUserExist({ user: { _id: '36', email: 'a@a.com' } }, { newMail: 'test@test.com' }); + await usersController.verifyUserExist({ user: { _id: '36', email: 'a@a.com' } }, { newMail: 'test@test.com' }); expect(spyer).toBeCalledTimes(1); }); }); @@ -358,7 +358,7 @@ describe('UsersController', () => { const isStructureClaimedSpyer = jest.spyOn(userServiceMock, 'isStructureClaimed'); const userWithoutStructure = usersMockData[2]; userServiceMock.deleteOne.mockResolvedValueOnce(userWithoutStructure); - await controller.delete({ user: { _id: '36', email: 'a@a.com' } }); + await usersController.delete({ user: { _id: '36', email: 'a@a.com' } }); expect(deleteOneSpyer).toBeCalledTimes(1); expect(isStructureClaimedSpyer).toBeCalledTimes(0); }); @@ -371,7 +371,7 @@ describe('UsersController', () => { userServiceMock.deleteOne.mockResolvedValueOnce(userWithThreeStructures); userServiceMock.isStructureClaimed.mockResolvedValue(null); userServiceMock.isStructureClaimed.mockResolvedValueOnce(userWithThreeStructures); - await controller.delete({ user: { _id: '36', email: 'a@a.com' } }); + await usersController.delete({ user: { _id: '36', email: 'a@a.com' } }); expect(userDeleteOneSpyer).toBeCalledTimes(1); expect(isStructureClaimedSpyer).toBeCalledTimes(3); expect(structureFindOne).toBeCalledTimes(2); @@ -381,7 +381,7 @@ describe('UsersController', () => { describe('dataConsentValidation', () => { it('should call getAllDataConsentPendingStructures', async () => { const spyer = jest.spyOn(structureServiceMock, 'getAllDataConsentPendingStructures'); - await controller.dataConsentValidation({ user: { _id: '36', email: 'a@a.com' } }); + await usersController.dataConsentValidation({ user: { _id: '36', email: 'a@a.com' } }); expect(spyer).toBeCalledTimes(1); }); }); @@ -390,7 +390,7 @@ describe('UsersController', () => { it('should return user', async () => { const spyer = jest.spyOn(userServiceMock, 'findById'); userServiceMock.findById.mockResolvedValueOnce({ _id: '36', email: 'a@a.com' }); - const result = await controller.getUser(1); + const result = await usersController.getUser(1); expect(result).toEqual({ _id: '36', email: 'a@a.com' }); expect(spyer).toBeCalledTimes(1); }); @@ -400,7 +400,7 @@ describe('UsersController', () => { userServiceMock.findById.mockResolvedValueOnce(null); try { - await controller.getUser(1); + await usersController.getUser(1); expect(true).toBe(false); } catch (error) { expect(error.message).toBe('User does not exist'); @@ -413,7 +413,7 @@ describe('UsersController', () => { describe('update description', () => { it('should call updateDescription', async () => { const spyer = jest.spyOn(userServiceMock, 'updateDescription'); - await controller.updateDescription({ user: { _id: '36', email: 'a@a.com' } }, new DescriptionDto()); + await usersController.updateDescription({ user: { _id: '36', email: 'a@a.com' } }, new DescriptionDto()); expect(spyer).toBeCalledTimes(1); }); }); diff --git a/src/users/services/employer-search.service.spec.ts b/src/users/services/employer-search.service.spec.ts index e41a421f04f0d512337527a498ee8042d41b61fd..3c6715978dda55e34e49608a5629b1bd1df1fa42 100644 --- a/src/users/services/employer-search.service.spec.ts +++ b/src/users/services/employer-search.service.spec.ts @@ -33,7 +33,7 @@ const employers = [ } as EmployerDocument, ]; describe('EmployerSearchService Search cases', () => { - let service: EmployerSearchService; + let employerSearchService: EmployerSearchService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ @@ -41,21 +41,21 @@ describe('EmployerSearchService Search cases', () => { providers: [EmployerSearchService], }).compile(); - service = module.get<EmployerSearchService>(EmployerSearchService); - service['index'] = 'employer-unit-test'; + employerSearchService = module.get<EmployerSearchService>(EmployerSearchService); + employerSearchService['index'] = 'employer-unit-test'; // Init test cases - await service.dropIndex(); - await service.createEmployerIndex(); - await Promise.all(employers.map((employer) => service.indexEmployer(employer))); + await employerSearchService.dropIndex(); + await employerSearchService.createEmployerIndex(); + await Promise.all(employers.map((employer) => employerSearchService.indexEmployer(employer))); // wait for the new structures to be indexed before search - await service.refreshIndexStructure(); + await employerSearchService.refreshIndexStructure(); await new Promise((r) => setTimeout(r, 2000)); }, 10000); it('should be defined', async () => { // await new Promise((r) => setTimeout(r, 9000)); - expect(service).toBeDefined(); + expect(employerSearchService).toBeDefined(); }); // it('should index structures', async () => { @@ -64,34 +64,34 @@ describe('EmployerSearchService Search cases', () => { // }, 10000); it('should find CARSAT', async () => { - const res = await service.search('CARSAT'); + const res = await employerSearchService.search('CARSAT'); expect(res[0].name).toBe('CARSAT'); expect(res.length).toBe(1); }); it('should find CAF', async () => { - const res = await service.search('CAF'); + const res = await employerSearchService.search('CAF'); expect(res[0].name).toBe('CAF'); expect(res.length).toBe(1); }); it('should index structures', async () => { - const res = await Promise.all(employers.map((employer) => service.indexEmployer(employer))); + const res = await Promise.all(employers.map((employer) => employerSearchService.indexEmployer(employer))); expect(res).toBeTruthy(); expect(res.length).toBe(5); }); it('should update index', async () => { - const resCaf = await service.search('CAF'); - const res = await service.update( + const resCaf = await employerSearchService.search('CAF'); + const res = await employerSearchService.update( resCaf[0] as EmployerDocument, new Types.ObjectId('6231aefe76598527c8d0b5bd').toHexString() ); expect(res).toBeTruthy(); }); it('should delete index', async () => { - const resCaf = await service.search('CAF'); - const res = await service.deleteIndex( + const resCaf = await employerSearchService.search('CAF'); + const res = await employerSearchService.deleteIndex( resCaf[0] as EmployerDocument, new Types.ObjectId('6231aefe76598527c8d0b5bd').toHexString() ); diff --git a/src/users/services/employer.service.spec.ts b/src/users/services/employer.service.spec.ts index ee6e05392aeee2cdbe9ca6bcd9b04d04d70aabc4..02f28a7a92f375d6ea936f614ccd0f8cb16a5d1a 100644 --- a/src/users/services/employer.service.spec.ts +++ b/src/users/services/employer.service.spec.ts @@ -14,8 +14,8 @@ import { EmployerService } from './employer.service'; import { UsersService } from './users.service'; describe('EmployerService', () => { - let service: EmployerService; - let mailer: MailerService; + let employerService: EmployerService; + let mailerService: MailerService; const mockEmployerSearchService = { indexEmployer: jest.fn(), @@ -61,12 +61,12 @@ describe('EmployerService', () => { MailerService, ], }).compile(); - service = module.get<EmployerService>(EmployerService); - mailer = module.get<MailerService>(MailerService); + employerService = module.get<EmployerService>(EmployerService); + mailerService = module.get<MailerService>(MailerService); }); it('should be defined', () => { - expect(service).toBeDefined(); + expect(employerService).toBeDefined(); }); it('findAll', async () => { @@ -83,7 +83,7 @@ describe('EmployerService', () => { validated: true, }, ]); - const reply = await service.findAll(); + const reply = await employerService.findAll(); expect(reply.length).toBe(2); }); it('findOne', async () => { @@ -93,7 +93,7 @@ describe('EmployerService', () => { name: 'Sopra', validated: true, }); - const reply = await service.findOne('6231aefe76598527c8d0b5bc'); + const reply = await employerService.findOne('6231aefe76598527c8d0b5bc'); expect(reply).toBeTruthy(); }); it('findAllValidated', async () => { @@ -105,7 +105,7 @@ describe('EmployerService', () => { validated: true, }, ]); - const reply = await service.findAllValidated(); + const reply = await employerService.findAllValidated(); expect(reply.length).toBe(1); }); @@ -118,7 +118,7 @@ describe('EmployerService', () => { validated: false, }, ]); - const reply = await service.findAllValidated(); + const reply = await employerService.findAllValidated(); expect(reply.length).toBe(1); }); @@ -131,7 +131,7 @@ describe('EmployerService', () => { validated: false, }, ]); - const reply = await service.findAllUnvalidated(); + const reply = await employerService.findAllUnvalidated(); expect(reply[0].validated).toBeFalsy; }); @@ -149,7 +149,7 @@ describe('EmployerService', () => { validated: true, }, ]); - const reply = await service.findAllUnvalidated(); + const reply = await employerService.findAllUnvalidated(); expect(reply.length).toBe(2); }); @@ -160,7 +160,7 @@ describe('EmployerService', () => { name: 'Sopra', validated: true, }); - const reply = await service.findByName('Sopra'); + const reply = await employerService.findByName('Sopra'); expect(reply).toBeTruthy(); }); @@ -180,10 +180,10 @@ describe('EmployerService', () => { const createEmployer: CreateEmployerDto = { name: 'Sopra', }; - jest.spyOn(service, 'sendAdminCreateNotification').mockResolvedValueOnce(); - const reply = await service.create(createEmployer); + jest.spyOn(employerService, 'sendAdminCreateNotification').mockResolvedValueOnce(); + const reply = await employerService.create(createEmployer); expect(reply).toBeTruthy(); - expect(service.sendAdminCreateNotification).toBeCalledTimes(1); + expect(employerService.sendAdminCreateNotification).toBeCalledTimes(1); }); it('should create validated employer and not send email to admins', async () => { @@ -201,7 +201,7 @@ describe('EmployerService', () => { const createEmployer: CreateEmployerDto = { name: 'Sopra', }; - const reply = await service.create(createEmployer, true, false); + const reply = await employerService.create(createEmployer, true, false); expect(reply).toBeTruthy(); }); }); @@ -220,14 +220,14 @@ describe('EmployerService', () => { deletedCount: 1, }); mockEmployerSearchService.deleteIndex.mockResolvedValueOnce({}); - const reply = await service.deleteByName('Sopra'); + const reply = await employerService.deleteByName('Sopra'); expect(reply).toBeTruthy(); }); describe('Search', () => { it('searchByName', async () => { mockEmployerSearchService.search.mockResolvedValue({ name: 'Sopra' }); - const reply = await service.searchByName('Sopra'); + const reply = await employerService.searchByName('Sopra'); expect(reply).toBeTruthy(); }); @@ -258,7 +258,7 @@ describe('EmployerService', () => { name: 'Sopra', validated: true, } as EmployerDocument); - const reply = await service.initEmployerIndex(); + const reply = await employerService.initEmployerIndex(); expect(reply).toBeTruthy(); expect(reply.length).toBe(2); }); @@ -285,7 +285,7 @@ describe('EmployerService', () => { validated: false, }); mockUserService.replaceEmployers.mockResolvedValueOnce(null); - const reply = await service.mergeEmployer({ + const reply = await employerService.mergeEmployer({ sourceEmployerId: '623aed68c5d45b6fbbaa7e60', targetEmployerId: '623aed68c5d45b6fbbaa7e61', }); @@ -299,10 +299,10 @@ describe('EmployerService', () => { }; mockEmployerModel.findById.mockReturnThis(); mockEmployerModel.exec.mockResolvedValueOnce(null).mockResolvedValueOnce(result); - jest.spyOn(service, 'deleteInvalidEmployer').mockRejectedValueOnce({}); + jest.spyOn(employerService, 'deleteInvalidEmployer').mockRejectedValueOnce({}); mockUserService.replaceEmployers.mockResolvedValueOnce(null); try { - await service.mergeEmployer({ + await employerService.mergeEmployer({ sourceEmployerId: '623aed68c5d45b6fbbaa7e60', targetEmployerId: '623aed68c5d45b6fbbaa7e61', }); @@ -333,8 +333,8 @@ describe('EmployerService', () => { headers: {}, config: {}, }; - jest.spyOn(mailer, 'send').mockResolvedValueOnce(result); - const spyer = jest.spyOn(mailer, 'send'); + jest.spyOn(mailerService, 'send').mockResolvedValueOnce(result); + const spyer = jest.spyOn(mailerService, 'send'); mockUserService.getAdmins.mockResolvedValueOnce([ { _id: '6231aefe76598527c8d0b5bc', @@ -349,7 +349,7 @@ describe('EmployerService', () => { personalOffers: [], }, ]); - await service.sendAdminCreateNotification( + await employerService.sendAdminCreateNotification( employer as EmployerDocument, 'adminEmployerCreate.ejs', 'adminEmployerCreate.json' @@ -367,14 +367,14 @@ describe('EmployerService', () => { validated: false, save: jest.fn().mockResolvedValueOnce(null), }); - const employer = await service.validate('623aed68c5d45b6fbbaa7e60'); + const employer = await employerService.validate('623aed68c5d45b6fbbaa7e60'); expect(employer.validated).toBe(true); }); it('should throw exception', async () => { mockEmployerModel.findById.mockReturnThis(); mockEmployerModel.exec.mockResolvedValueOnce(null); try { - await service.validate('623aed68c5d45b6fbbaa7e60'); + await employerService.validate('623aed68c5d45b6fbbaa7e60'); expect(true).toBe(false); } catch (e) { expect(e.message).toBe('Cannot validate employer. It might have been already validate'); @@ -392,14 +392,14 @@ describe('EmployerService', () => { validated: false, save: jest.fn().mockResolvedValueOnce(null), }); - const employer = await service.update('623aed68c5d45b6fbbaa7e60', { name: 'Sopra' }); + const employer = await employerService.update('623aed68c5d45b6fbbaa7e60', { name: 'Sopra' }); expect(employer.name).toBe('Sopra'); }); it('should throw exception', async () => { mockEmployerModel.findById.mockReturnThis(); mockEmployerModel.exec.mockResolvedValueOnce(null); try { - await service.update('623aed68c5d45b6fbbaa7e60', { name: 'Sopra' }); + await employerService.update('623aed68c5d45b6fbbaa7e60', { name: 'Sopra' }); expect(true).toBe(false); } catch (e) { expect(e.message).toBe('Cannot edit employer. It was not found in database.'); @@ -425,7 +425,7 @@ describe('EmployerService', () => { validated: false, save: jest.fn().mockResolvedValueOnce(null), }); - await service.deleteInvalidEmployer('6231aefe76598527c8d0b5bc'); + await employerService.deleteInvalidEmployer('6231aefe76598527c8d0b5bc'); expect(mockEmployerSearchService.deleteIndex).toBeCalled(); expect(mockEmployerModel.deleteOne).toBeCalled(); }); @@ -458,7 +458,7 @@ describe('EmployerService', () => { personalOffers: [], }), }); - expect(await service.deleteOneId('6231aefe76598527c8d0b5bc')).toStrictEqual({ + expect(await employerService.deleteOneId('6231aefe76598527c8d0b5bc')).toStrictEqual({ _id: '6231aefe76598527c8d0b5bc', validationToken: 'cf1c74c22cedb6b575945098db42d2f493fb759c9142c6aff7980f252886f36ee086574ee99a06bc99119079257116c959c8ec870949cebdef2b293666dbca42', @@ -476,7 +476,7 @@ describe('EmployerService', () => { mockEmployerModel.exec.mockResolvedValueOnce(null); try { - expect(await service.deleteOneId('6231aefe76598527c8d0b5bc')).toStrictEqual({ + expect(await employerService.deleteOneId('6231aefe76598527c8d0b5bc')).toStrictEqual({ _id: '6231aefe76598527c8d0b5bc', validationToken: 'cf1c74c22cedb6b575945098db42d2f493fb759c9142c6aff7980f252886f36ee086574ee99a06bc99119079257116c959c8ec870949cebdef2b293666dbca42', diff --git a/src/users/services/jobs.service.spec.ts b/src/users/services/jobs.service.spec.ts index 9d53daca0de9d26aa775d9942959dee707606fa1..5729d503ffb339e8a8d9e726cd4ec34d8b25c92a 100644 --- a/src/users/services/jobs.service.spec.ts +++ b/src/users/services/jobs.service.spec.ts @@ -10,13 +10,13 @@ import { MailerService } from '../../mailer/mailer.service'; import { CreateJobDto } from '../dto/create-job.dto'; import { JobDocument } from '../schemas/job.schema'; import { JobsService } from './jobs.service'; -import { UsersService } from './users.service'; import { JobsGroupsService } from './jobsGroups.service'; +import { UsersService } from './users.service'; describe('JobsService', () => { - let service: JobsService; + let jobsService: JobsService; let httpService: HttpService; - let mailer: MailerService; + let mailerService: MailerService; const mockJobModel = { create: jest.fn(), @@ -68,13 +68,13 @@ describe('JobsService', () => { MailerService, ], }).compile(); - service = module.get<JobsService>(JobsService); - mailer = module.get<MailerService>(MailerService); + jobsService = module.get<JobsService>(JobsService); + mailerService = module.get<MailerService>(MailerService); httpService = module.get<HttpService>(HttpService); }); it('should be defined', () => { - expect(service).toBeDefined(); + expect(jobsService).toBeDefined(); }); describe('findAll', () => { @@ -89,7 +89,7 @@ describe('JobsService', () => { }, ]; mockJobModel.exec.mockResolvedValueOnce(result); - const reply = await service.findAll(); + const reply = await jobsService.findAll(); expect(reply.length).toBe(1); }); it('should findAll all jobs', async () => { @@ -103,7 +103,7 @@ describe('JobsService', () => { }, ]; mockJobModel.exec.mockResolvedValueOnce(result); - const reply = await service.findAll(false); + const reply = await jobsService.findAll(false); expect(reply.length).toBe(1); }); }); @@ -118,7 +118,7 @@ describe('JobsService', () => { jobsGroup: null, }, ]); - const reply = await service.findAllUnvalidated(); + const reply = await jobsService.findAllUnvalidated(); expect(reply[0].validated).toBeFalsy; }); @@ -130,7 +130,7 @@ describe('JobsService', () => { hasPersonalOffer: true, jobsGroup: null, }); - const reply = await service.findByName('CNFS'); + const reply = await jobsService.findByName('CNFS'); expect(reply).toBeTruthy(); }); it('findOne', async () => { @@ -141,7 +141,7 @@ describe('JobsService', () => { hasPersonalOffer: true, jobsGroup: null, }); - const reply = await service.findOne('6231aefe76598527c8d0b5bc'); + const reply = await jobsService.findOne('6231aefe76598527c8d0b5bc'); expect(reply).toBeTruthy(); }); @@ -173,7 +173,7 @@ describe('JobsService', () => { personalOffers: [], }, ]); - const reply = await service.create(createJob); + const reply = await jobsService.create(createJob); expect(reply).toBeTruthy(); }); @@ -193,7 +193,7 @@ describe('JobsService', () => { config: {}, }; jest.spyOn(httpService, 'post').mockImplementationOnce(() => of(result)); - expect(await mailer.send('a@a.com', 'test', '<p>This is a test</p>')).toBe(result.data); + expect(await mailerService.send('a@a.com', 'test', '<p>This is a test</p>')).toBe(result.data); }); }); @@ -224,7 +224,7 @@ describe('JobsService', () => { personalOffers: [], }, ]); - const reply = await service.create(createJob); + const reply = await jobsService.create(createJob); expect(reply).toBeTruthy(); }); @@ -248,8 +248,8 @@ describe('JobsService', () => { headers: {}, config: {}, }; - jest.spyOn(mailer, 'send').mockResolvedValueOnce(result); - const spyer = jest.spyOn(mailer, 'send'); + jest.spyOn(mailerService, 'send').mockResolvedValueOnce(result); + const spyer = jest.spyOn(mailerService, 'send'); mockUserService.getAdmins.mockResolvedValueOnce([ { _id: '6231aefe76598527c8d0b5bc', @@ -264,7 +264,7 @@ describe('JobsService', () => { personalOffers: [], }, ]); - await service.sendAdminCreateNotification(job as JobDocument, 'adminJobCreate.ejs', 'adminJobCreate.json'); + await jobsService.sendAdminCreateNotification(job as JobDocument, 'adminJobCreate.ejs', 'adminJobCreate.json'); expect(spyer.mock.calls.length).toBe(1); }); }); @@ -277,13 +277,13 @@ describe('JobsService', () => { validated: false, save: jest.fn().mockResolvedValueOnce(null), }); - const job = await service.validate('623aed68c5d45b6fbbaa7e60'); + const job = await jobsService.validate('623aed68c5d45b6fbbaa7e60'); expect(job.validated).toBe(true); }); it('should throw exception', async () => { mockJobModel.exec.mockResolvedValueOnce(null); try { - await service.validate('623aed68c5d45b6fbbaa7e60'); + await jobsService.validate('623aed68c5d45b6fbbaa7e60'); expect(true).toBe(false); } catch (e) { expect(e.message).toBe('Cannot validate job. It might have been already validate'); @@ -312,7 +312,7 @@ describe('JobsService', () => { .mockResolvedValueOnce(result); try { - const reply = await service.mergeJob({ + const reply = await jobsService.mergeJob({ sourceJobId: '623aed68c5d45b6fbbaa7e60', targetJobId: '623aed68c5d45b6fbbaa7e61', }); @@ -332,7 +332,10 @@ describe('JobsService', () => { }) .mockResolvedValueOnce(null); try { - await service.mergeJob({ sourceJobId: '623aed68c5d45b6fbbaa7e60', targetJobId: '623aed68c5d45b6fbbaa7e61' }); + await jobsService.mergeJob({ + sourceJobId: '623aed68c5d45b6fbbaa7e60', + targetJobId: '623aed68c5d45b6fbbaa7e61', + }); expect(true).toBe(false); } catch (e) { expect(e.message).toBe('Cannot operate on job.'); @@ -348,7 +351,10 @@ describe('JobsService', () => { jobsGroup: null, }); try { - await service.mergeJob({ sourceJobId: '623aed68c5d45b6fbbaa7e60', targetJobId: '623aed68c5d45b6fbbaa7e61' }); + await jobsService.mergeJob({ + sourceJobId: '623aed68c5d45b6fbbaa7e60', + targetJobId: '623aed68c5d45b6fbbaa7e61', + }); expect(true).toBe(false); } catch (e) { expect(e.message).toBe('Cannot operate on job.'); @@ -359,8 +365,8 @@ describe('JobsService', () => { it('deleteInvalidJob', async () => { mockJobModel.exec.mockResolvedValueOnce(null); - const spyer = jest.spyOn(service, 'deleteInvalidJob'); - await service.deleteInvalidJob('623aed68c5d45b6fbbaa7e60'); + const spyer = jest.spyOn(jobsService, 'deleteInvalidJob'); + await jobsService.deleteInvalidJob('623aed68c5d45b6fbbaa7e60'); expect(spyer.mock.calls.length).toEqual(1); }); @@ -372,13 +378,13 @@ describe('JobsService', () => { validated: false, deleteOne: jest.fn().mockResolvedValueOnce('toto'), }); - const reply = await service.deleteOneId('623aed68c5d45b6fbbaa7e60'); + const reply = await jobsService.deleteOneId('623aed68c5d45b6fbbaa7e60'); expect(reply).toBe('toto'); }); it('should delete ', async () => { mockJobModel.exec.mockResolvedValueOnce(null); try { - await service.deleteOneId('623aed68c5d45b6fbbaa7e60'); + await jobsService.deleteOneId('623aed68c5d45b6fbbaa7e60'); expect(true).toBe(false); } catch (e) { expect(e.message).toBe('Invalid job id'); @@ -409,7 +415,7 @@ describe('JobsService', () => { jobsGroup: null, save: jest.fn().mockResolvedValueOnce(newJob), }); - const reply = await service.update('623aed68c5d45b6fbbaa7e60', newJobDto); + const reply = await jobsService.update('623aed68c5d45b6fbbaa7e60', newJobDto); expect(reply.name).toBe('CNFS'); expect(reply.hasPersonalOffer).toBe(true); }); @@ -423,7 +429,7 @@ describe('JobsService', () => { }; mockJobModel.exec.mockResolvedValueOnce(null); try { - await service.update('623aed68c5d45b6fbbaa7e60', newJobDto); + await jobsService.update('623aed68c5d45b6fbbaa7e60', newJobDto); expect(true).toBe(false); } catch (e) { expect(e.message).toBe('Cannot edit job. It was not found in database.'); diff --git a/src/users/services/jobsGroups.service.spec.ts b/src/users/services/jobsGroups.service.spec.ts index ee25b30ddf2196b67351dfb80629611f4b52ebcf..0efb723e8c35e6313c7ecc9c8a8c8fddff176c57 100644 --- a/src/users/services/jobsGroups.service.spec.ts +++ b/src/users/services/jobsGroups.service.spec.ts @@ -6,12 +6,12 @@ import { Types } from 'mongoose'; import { ConfigurationModule } from '../../configuration/configuration.module'; import { MailerService } from '../../mailer/mailer.service'; import { CreateJobsGroupsDto } from '../dto/create-jobsGroups.dto'; +import { JobsService } from './jobs.service'; import { JobsGroupsService } from './jobsGroups.service'; import { UsersService } from './users.service'; -import { JobsService } from './jobs.service'; describe('JobsGroupsService', () => { - let service: JobsGroupsService; + let jobsGroupsService: JobsGroupsService; const mockJobsGroupsModel = { create: jest.fn(), @@ -71,11 +71,11 @@ describe('JobsGroupsService', () => { MailerService, ], }).compile(); - service = module.get<JobsGroupsService>(JobsGroupsService); + jobsGroupsService = module.get<JobsGroupsService>(JobsGroupsService); }); it('should be defined', () => { - expect(service).toBeDefined(); + expect(jobsGroupsService).toBeDefined(); }); describe('findAll', () => { @@ -87,7 +87,7 @@ describe('JobsGroupsService', () => { }, ]; mockJobsGroupsModel.exec.mockResolvedValueOnce(result); - const reply = await service.findAll(false); + const reply = await jobsGroupsService.findAll(false); expect(reply.length).toBe(1); }); }); @@ -97,7 +97,7 @@ describe('JobsGroupsService', () => { _id: new Types.ObjectId('6231aefe76598527c8d0b5bc'), name: 'Technique', }); - const reply = await service.findByName('Technique'); + const reply = await jobsGroupsService.findByName('Technique'); expect(reply).toBeTruthy(); }); it('findOne', async () => { @@ -105,7 +105,7 @@ describe('JobsGroupsService', () => { _id: new Types.ObjectId('6231aefe76598527c8d0b5bc'), name: 'Technique', }); - const reply = await service.findOne('6231aefe76598527c8d0b5bc'); + const reply = await jobsGroupsService.findOne('6231aefe76598527c8d0b5bc'); expect(reply).toBeTruthy(); }); @@ -118,7 +118,7 @@ describe('JobsGroupsService', () => { const createJobsGroups: CreateJobsGroupsDto = { name: 'Technique', }; - const reply = await service.create(createJobsGroups); + const reply = await jobsGroupsService.create(createJobsGroups); expect(reply).toBeTruthy(); }); }); @@ -137,7 +137,7 @@ describe('JobsGroupsService', () => { name: 'Technique old', save: jest.fn().mockResolvedValueOnce(newJobsGroups), }); - const reply = await service.update('623aed68c5d45b6fbbaa7e60', newJobsGroupsDto); + const reply = await jobsGroupsService.update('623aed68c5d45b6fbbaa7e60', newJobsGroupsDto); expect(reply.name).toBe('Technique'); }); }); @@ -148,7 +148,7 @@ describe('JobsGroupsService', () => { }; mockJobsGroupsModel.exec.mockResolvedValueOnce(null); try { - await service.update('623aed68c5d45b6fbbaa7e60', newJobsGroupsDto); + await jobsGroupsService.update('623aed68c5d45b6fbbaa7e60', newJobsGroupsDto); expect(true).toBe(false); } catch (e) { expect(e.status).toBe(HttpStatus.NOT_FOUND); diff --git a/src/users/services/userRegistry-search.service.spec.ts b/src/users/services/userRegistry-search.service.spec.ts index 0a6829c76649d9475292376fc7325ab671cdef97..16473e92be3edfa31092ff0f1c0f38008888196e 100644 --- a/src/users/services/userRegistry-search.service.spec.ts +++ b/src/users/services/userRegistry-search.service.spec.ts @@ -6,7 +6,7 @@ import { IUserRegistry } from '../interfaces/userRegistry.interface'; import { UserRegistrySearchService } from './userRegistry-search.service'; describe('UserRegistrySearchService Search cases', () => { - let service: UserRegistrySearchService; + let userRegistrySearchService: UserRegistrySearchService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ @@ -14,50 +14,50 @@ describe('UserRegistrySearchService Search cases', () => { providers: [UserRegistrySearchService], }).compile(); - service = module.get<UserRegistrySearchService>(UserRegistrySearchService); - service['index'] = 'user-unit-test'; + userRegistrySearchService = module.get<UserRegistrySearchService>(UserRegistrySearchService); + userRegistrySearchService['index'] = 'user-unit-test'; // Init test cases - await service.dropIndex(); - await service.createUserRegistryIndex(); - await Promise.all(multipleUsers.map((user) => service.indexUserRegistry(user))); + await userRegistrySearchService.dropIndex(); + await userRegistrySearchService.createUserRegistryIndex(); + await Promise.all(multipleUsers.map((user) => userRegistrySearchService.indexUserRegistry(user))); // wait for the new structures to be indexed before search - await service.refreshIndexUserRegistry(); + await userRegistrySearchService.refreshIndexUserRegistry(); await new Promise((r) => setTimeout(r, 2000)); }, 10000); it('should be defined', async () => { - expect(service).toBeDefined(); + expect(userRegistrySearchService).toBeDefined(); }); describe('Search method', () => { it('should find Guilhem', async () => { - const res = await service.search('Guilhem'); + const res = await userRegistrySearchService.search('Guilhem'); expect(res[0].surname).toBe('Guilhem'); expect(res.length).toBe(1); }); it('should find adm', async () => { - const res = await service.search('adm'); + const res = await userRegistrySearchService.search('adm'); expect(res[0].name).toBe('Admin'); expect(res.length).toBe(1); }); it('should find empty string', async () => { - const res = await service.search(''); + const res = await userRegistrySearchService.search(''); expect(res.length).toBe(6); }); }); describe('Indexation methods', () => { it('should index User', async () => { - const res = await Promise.all(multipleUsers.map((user) => service.indexUserRegistry(user))); + const res = await Promise.all(multipleUsers.map((user) => userRegistrySearchService.indexUserRegistry(user))); expect(res).toBeTruthy(); expect(res.length).toBe(6); }); it('should update index', async () => { - const res = await service.update(multipleUsers[0] as IUserRegistry); + const res = await userRegistrySearchService.update(multipleUsers[0] as IUserRegistry); expect(res).toBeTruthy(); }); it('should delete index', async () => { - const resAdm = await service.search('adm'); - const res = await service.deleteIndex(resAdm[0] as IUserRegistry); + const resAdm = await userRegistrySearchService.search('adm'); + const res = await userRegistrySearchService.deleteIndex(resAdm[0] as IUserRegistry); expect(res).toBeTruthy(); }); }); diff --git a/src/users/services/userRegistry.service.spec.ts b/src/users/services/userRegistry.service.spec.ts index 9680741baf340e2b8cfac5378fb779495f2b84b7..7cca791d156e5fd927081caedf7a68f161e4f333 100644 --- a/src/users/services/userRegistry.service.spec.ts +++ b/src/users/services/userRegistry.service.spec.ts @@ -11,7 +11,7 @@ import { UserRegistrySearchService } from './userRegistry-search.service'; import { UserRegistryService } from './userRegistry.service'; describe('userRegistryService', () => { - let service: UserRegistryService; + let userRegistryService: UserRegistryService; const mockUserRegistryModel = { find: jest.fn(() => mockUserRegistryModel), where: jest.fn(() => mockUserRegistryModel), @@ -62,11 +62,11 @@ describe('userRegistryService', () => { }, ], }).compile(); - service = module.get<UserRegistryService>(UserRegistryService); + userRegistryService = module.get<UserRegistryService>(UserRegistryService); }); it('should be defined', () => { - expect(service).toBeDefined(); + expect(userRegistryService).toBeDefined(); }); describe('findAll', () => { @@ -88,18 +88,18 @@ describe('userRegistryService', () => { ] as IUserRegistry[]; it('should findAll UserRegistry for indexation', async () => { mockUserRegistryModel.exec.mockResolvedValueOnce(result); - expect(await service.findAllForIndexation()).toBe(result); + expect(await userRegistryService.findAllForIndexation()).toBe(result); }); it('should findAll UserRegistry count', async () => { mockUserRegistryModel.exec.mockResolvedValueOnce(result.length); - expect(await service.countAllUserRegistry()).toBe(result.length); + expect(await userRegistryService.countAllUserRegistry()).toBe(result.length); }); it('should findAllUserRegistry with page number 1', async () => { const res = { count: 1, docs: result }; mockUserRegistryModel.exec.mockResolvedValueOnce(1); mockUserRegistryModel.exec.mockResolvedValueOnce(result); - expect(await service.findAllUserRegistry(1)).toStrictEqual(res); + expect(await userRegistryService.findAllUserRegistry(1)).toStrictEqual(res); }); }); describe('find with filter', () => { @@ -142,13 +142,13 @@ describe('userRegistryService', () => { it('should findUsersByNameEmployerOrJobsGroup with string param and get a result', async () => { mockUserRegistryModel.exec.mockResolvedValueOnce(result); mockUserRegistrySearchService.search.mockResolvedValueOnce(result); - expect(await service.findUsersByNameEmployerOrJobsGroup('adm', 1)).toStrictEqual(res); + expect(await userRegistryService.findUsersByNameEmployerOrJobsGroup('adm', 1)).toStrictEqual(res); }); it('should findUsersByNameEmployerOrJobsGroup with string param and get no result', async () => { const emptyRes = { count: 0, docs: [] }; mockUserRegistryModel.exec.mockResolvedValueOnce([]); mockUserRegistrySearchService.search.mockResolvedValueOnce([]); - expect(await service.findUsersByNameEmployerOrJobsGroup('azerty', 1)).toStrictEqual(emptyRes); + expect(await userRegistryService.findUsersByNameEmployerOrJobsGroup('azerty', 1)).toStrictEqual(emptyRes); }); it('should findUsersByNameEmployerOrJobsGroup with no string param and filters', async () => { const res = { count: 1, docs: [multipleUsers[1]] }; @@ -163,7 +163,9 @@ describe('userRegistryService', () => { mockJobsGroupsService.findByName.mockResolvedValueOnce(jobGroupList[0]); mockEmployersService.findByName.mockResolvedValueOnce(employerList[0]); mockUserRegistryModel.exec.mockResolvedValueOnce(multipleUsers); - expect(await service.findUsersByNameEmployerOrJobsGroup('', 1, ['Technique'], ['Métropole'])).toStrictEqual(res); + expect( + await userRegistryService.findUsersByNameEmployerOrJobsGroup('', 1, ['Technique'], ['Métropole']) + ).toStrictEqual(res); }); it('should findUsersByNameEmployerOrJobsGroup with string param and filters', async () => { @@ -179,9 +181,9 @@ describe('userRegistryService', () => { mockJobsGroupsService.findByName.mockResolvedValueOnce(jobGroupList[0]); mockEmployersService.findByName.mockResolvedValueOnce(employerList[0]); mockUserRegistryModel.exec.mockResolvedValueOnce(multipleUsers); - expect(await service.findUsersByNameEmployerOrJobsGroup('Guil', 1, ['Technique'], ['Métropole'])).toStrictEqual( - res - ); + expect( + await userRegistryService.findUsersByNameEmployerOrJobsGroup('Guil', 1, ['Technique'], ['Métropole']) + ).toStrictEqual(res); }); it('should findUsersByNameEmployerOrJobsGroup with string param and filters and return empty', async () => { const res = { count: 0, docs: [] }; @@ -197,7 +199,7 @@ describe('userRegistryService', () => { mockEmployersService.findByName.mockResolvedValueOnce(employerList[0]); mockUserRegistryModel.exec.mockResolvedValueOnce([]); expect( - await service.findUsersByNameEmployerOrJobsGroup('azerrttt', 1, ['Technique'], ['Métropole']) + await userRegistryService.findUsersByNameEmployerOrJobsGroup('azerrttt', 1, ['Technique'], ['Métropole']) ).toStrictEqual(res); }); it('should findUsersByNameEmployerOrJobsGroup with string param and one employer filter', async () => { @@ -206,7 +208,7 @@ describe('userRegistryService', () => { mockUserRegistrySearchService.search.mockResolvedValueOnce(multipleUsers); mockEmployersService.findByName.mockResolvedValueOnce(employerList[0]); mockUserRegistryModel.exec.mockResolvedValueOnce(multipleUsers); - expect(await service.findUsersByNameEmployerOrJobsGroup('a', 1, [], ['CAF'])).toStrictEqual(res); + expect(await userRegistryService.findUsersByNameEmployerOrJobsGroup('a', 1, [], ['CAF'])).toStrictEqual(res); }); it('should findUsersByNameEmployerOrJobsGroup with no string param and one jobsGroup filter', async () => { @@ -220,7 +222,7 @@ describe('userRegistryService', () => { mockUserRegistrySearchService.search.mockResolvedValueOnce(multipleUsers); mockJobsGroupsService.findByName.mockResolvedValueOnce(jobGroupList[0]); mockUserRegistryModel.exec.mockResolvedValueOnce(multipleUsers); - expect(await service.findUsersByNameEmployerOrJobsGroup('', 1, ['Technique'], [])).toStrictEqual(res); + expect(await userRegistryService.findUsersByNameEmployerOrJobsGroup('', 1, ['Technique'], [])).toStrictEqual(res); }); }); @@ -230,13 +232,13 @@ describe('userRegistryService', () => { mockUserRegistrySearchService.dropIndex.mockResolvedValueOnce({}); mockUserRegistrySearchService.createUserRegistryIndex.mockResolvedValueOnce({}); mockUserRegistrySearchService.indexUserRegistry.mockResolvedValueOnce({}); - expect(await service.initUserRegistryIndex()).toBe(multipleUsers); + expect(await userRegistryService.initUserRegistryIndex()).toBe(multipleUsers); }); it('should findAllUserRegistry with page number 1', async () => { mockUserRegistrySearchService.search.mockResolvedValueOnce([multipleUsers[0]]); - expect(await service.searchByNameAndSurname('adm')).toStrictEqual([multipleUsers[0]]); + expect(await userRegistryService.searchByNameAndSurname('adm')).toStrictEqual([multipleUsers[0]]); }); }); }); diff --git a/src/users/services/users.service.spec.ts b/src/users/services/users.service.spec.ts index 0b7bf0db046eacc859df151fff7093f3a6401b13..f3e695b9d69c4a0a3e522d05bfb16c9ca810c399 100644 --- a/src/users/services/users.service.spec.ts +++ b/src/users/services/users.service.spec.ts @@ -1,4 +1,3 @@ -import { cnfsJobMock } from './../../../test/mock/data/jobs.mock.data'; import { HttpModule } from '@nestjs/axios'; import { HttpException, HttpStatus } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; @@ -10,11 +9,13 @@ import { employersMockData } from '../../../test/mock/data/employers.mock.data'; import { personalOffersDataMock } from '../../../test/mock/data/personalOffers.mock.data'; import { userDetails, userRegistryMockData, usersMockData } from '../../../test/mock/data/users.mock.data'; import { MailerMockService } from '../../../test/mock/services/mailer.mock.service'; +import { StructuresServiceMock } from '../../../test/mock/services/structures.mock.service'; import { LoginDto } from '../../auth/login-dto'; import { ConfigurationModule } from '../../configuration/configuration.module'; import { MailerModule } from '../../mailer/mailer.module'; import { MailerService } from '../../mailer/mailer.service'; import { PersonalOfferDocument } from '../../personal-offers/schemas/personal-offer.schema'; +import { StructuresService } from '../../structures/services/structures.service'; import { CreateUserDto } from '../dto/create-user.dto'; import { DescriptionDto } from '../dto/description.dto'; import { UpdateDetailsDto } from '../dto/update-details.dto'; @@ -22,11 +23,10 @@ import { IUser } from '../interfaces/user.interface'; import { EmployerDocument } from '../schemas/employer.schema'; import { JobDocument } from '../schemas/job.schema'; import { User } from '../schemas/user.schema'; +import { cnfsJobMock } from './../../../test/mock/data/jobs.mock.data'; +import { JobsService } from './jobs.service'; import { UserRegistrySearchService } from './userRegistry-search.service'; import { UsersService } from './users.service'; -import { JobsService } from './jobs.service'; -import { StructuresService } from '../../structures/services/structures.service'; -import { StructuresServiceMock } from '../../../test/mock/services/structures.mock.service'; function hashPassword() { return bcrypt.hashSync(process.env.USER_PWD, process.env.SALT); @@ -127,7 +127,7 @@ const mockJobsService = { }; describe('UsersService', () => { - let service: UsersService; + let usersService: UsersService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ @@ -159,21 +159,21 @@ describe('UsersService', () => { ], }).compile(); - service = module.get<UsersService>(UsersService); + usersService = module.get<UsersService>(UsersService); }); afterEach(() => { jest.clearAllMocks(); }); it('UsersService should be defined', () => { - expect(service).toBeDefined(); + expect(usersService).toBeDefined(); }); describe('create', () => { it('should not create a User, already exist', async () => { - jest.spyOn(service, 'findOne').mockImplementationOnce(async (): Promise<any> => createUserDto); + jest.spyOn(usersService, 'findOne').mockImplementationOnce(async (): Promise<any> => createUserDto); try { - await service.create(createUserDto); + await usersService.create(createUserDto); expect(true).toBe(false); } catch (error) { expect(error.status).toBe(HttpStatus.BAD_REQUEST); @@ -182,10 +182,10 @@ describe('UsersService', () => { }); it('should not create User, weak password', async () => { - jest.spyOn(service, 'findOne').mockImplementationOnce(async () => null); - jest.spyOn(service, 'isStrongPassword').mockImplementationOnce(() => false); + jest.spyOn(usersService, 'findOne').mockImplementationOnce(async () => null); + jest.spyOn(usersService, 'isStrongPassword').mockImplementationOnce(() => false); try { - await service.create(createUserDto); + await usersService.create(createUserDto); expect(true).toBe(false); } catch (error) { expect(error.status).toBe(HttpStatus.UNPROCESSABLE_ENTITY); @@ -195,59 +195,59 @@ describe('UsersService', () => { } }); it('should create a User', async () => { - jest.spyOn(service, 'findOne').mockImplementationOnce(async () => null); - jest.spyOn(service, 'isStrongPassword').mockImplementationOnce(() => true); + jest.spyOn(usersService, 'findOne').mockImplementationOnce(async () => null); + jest.spyOn(usersService, 'isStrongPassword').mockImplementationOnce(() => true); //TODO mock new userModal(createUserDto) return; - jest.spyOn(service, 'findOne').mockImplementationOnce(async (): Promise<any> => mockUser); - expect(await service.create(createUserDto)).toBe(mockUser); + jest.spyOn(usersService, 'findOne').mockImplementationOnce(async (): Promise<any> => mockUser); + expect(await usersService.create(createUserDto)).toBe(mockUser); }); }); describe('isStrongPassword', () => { it('should return false with "AZERTYU1" (no lowercase character)', () => { - expect(service.isStrongPassword('AZERTY')).toBe(false); + expect(usersService.isStrongPassword('AZERTY')).toBe(false); }); it('should return false with "azertyu1" (no uppercase character)', () => { - expect(service.isStrongPassword('azerty')).toBe(false); + expect(usersService.isStrongPassword('azerty')).toBe(false); }); it('should return false with "azertyui" (no number)', () => { - expect(service.isStrongPassword('azerty')).toBe(false); + expect(usersService.isStrongPassword('azerty')).toBe(false); }); it('should return false with "azertyu1" (no special character)', () => { - expect(service.isStrongPassword('azertyu1')).toBe(false); + expect(usersService.isStrongPassword('azertyu1')).toBe(false); }); it('should return false with "azertyu1" (no special character)', () => { - expect(service.isStrongPassword('azertyu1')).toBe(false); + expect(usersService.isStrongPassword('azertyu1')).toBe(false); }); it('should return false with "azer" (too short)', () => { - expect(service.isStrongPassword('azer')).toBe(false); + expect(usersService.isStrongPassword('azer')).toBe(false); }); it('should return true with "Azerty1!', () => { - expect(service.isStrongPassword('Azerty1!')).toBe(true); + expect(usersService.isStrongPassword('Azerty1!')).toBe(true); }); }); describe('findOne', () => { it('should find one user', async () => { mockUserModel.exec.mockResolvedValue(mockUser); - expect(await service.findOne('some@mail.com')).toBe(mockUser); + expect(await usersService.findOne('some@mail.com')).toBe(mockUser); }); }); describe('findAll', () => { it('should find all users', async () => { mockUserModel.exec.mockResolvedValue(usersMockData); - expect(await service.findAll()).toBe(usersMockData); + expect(await usersService.findAll()).toBe(usersMockData); }); }); describe('findByLogin', () => { const loginDto: LoginDto = { email: 'jacques.dupont@mii.com', password: 'test1A!!' }; it('should fail, no user found', async () => { - jest.spyOn(service, 'findOne').mockResolvedValue(null); + jest.spyOn(usersService, 'findOne').mockResolvedValue(null); try { - await service.findByLogin(loginDto); + await usersService.findByLogin(loginDto); expect(true).toBe(false); } catch (error) { expect(error.status).toBe(HttpStatus.UNAUTHORIZED); @@ -256,11 +256,11 @@ describe('UsersService', () => { }); it('should fail, wrong password', async () => { - jest.spyOn(service, 'findOne').mockResolvedValue(mockUser as IUser); + jest.spyOn(usersService, 'findOne').mockResolvedValue(mockUser as IUser); //TODO mock private function comparePassword ? -> false return true; try { - await service.findByLogin(loginDto); + await usersService.findByLogin(loginDto); expect(true).toBe(false); } catch (error) { expect(error.status).toBe(HttpStatus.UNAUTHORIZED); @@ -270,18 +270,18 @@ describe('UsersService', () => { it('should find', async () => { mockUserModel.findOne.mockResolvedValue(mockUser); - jest.spyOn(service, 'findOne').mockResolvedValue(mockUser as IUser); + jest.spyOn(usersService, 'findOne').mockResolvedValue(mockUser as IUser); //TODO mock private function comparePassword ? -> true return true; - expect(await service.findByLogin(loginDto)).toBe(mockUser); + expect(await usersService.findByLogin(loginDto)).toBe(mockUser); }); it('wrong password, should be unauthorized issue', async () => { const result: HttpException = new HttpException('Invalid credentials', HttpStatus.UNAUTHORIZED); const loginDto: LoginDto = { email: 'jacques.dupont@mii.com', password: 'test1A!!!' }; //NOSONAR - jest.spyOn(service, 'findOne').mockResolvedValue(null); + jest.spyOn(usersService, 'findOne').mockResolvedValue(null); try { - await service.findByLogin(loginDto); + await usersService.findByLogin(loginDto); expect(true).toBe(false); } catch (error) { expect(error.status).toBe(HttpStatus.UNAUTHORIZED); @@ -294,8 +294,8 @@ describe('UsersService', () => { // TODO implement correct tests it('should not validateUser', async () => { const result = new HttpException('Invalid token', HttpStatus.UNAUTHORIZED); - jest.spyOn(service, 'validateUser').mockImplementation(async (): Promise<HttpException> => result); - expect(await service.validateUser('add3d', 'qdqdqdqd185')).toBe(result); + jest.spyOn(usersService, 'validateUser').mockImplementation(async (): Promise<HttpException> => result); + expect(await usersService.validateUser('add3d', 'qdqdqdqd185')).toBe(result); }); }); @@ -330,16 +330,16 @@ describe('UsersService', () => { describe('addPersonalOffer', () => { const personalOfferDocumentMock: PersonalOfferDocument = personalOffersDataMock[0] as PersonalOfferDocument; it('should add personal offer to the user', async () => { - jest.spyOn(service, 'findById').mockResolvedValue(usersMockData[0]); + jest.spyOn(usersService, 'findById').mockResolvedValue(usersMockData[0]); const expectedResult = { ...usersMockData[0], personalOffers: [personalOfferDocumentMock] }; - expect(await service.addPersonalOffer('6036721022462b001334c4bb', personalOfferDocumentMock)).toEqual( + expect(await usersService.addPersonalOffer('6036721022462b001334c4bb', personalOfferDocumentMock)).toEqual( expectedResult ); }); it('should return exception if user is not found for given id', async () => { - jest.spyOn(service, 'findById').mockResolvedValue(null); + jest.spyOn(usersService, 'findById').mockResolvedValue(null); try { - await service.addPersonalOffer('abcd', personalOfferDocumentMock); + await usersService.addPersonalOffer('abcd', personalOfferDocumentMock); // Fail test if above expression doesn't throw anything. expect(true).toBe(false); } catch (e) { @@ -348,9 +348,9 @@ describe('UsersService', () => { } }); it('should return exception if personal offer already exists in the user', async () => { - jest.spyOn(service, 'findById').mockResolvedValue(usersMockData[1]); + jest.spyOn(usersService, 'findById').mockResolvedValue(usersMockData[1]); try { - await service.addPersonalOffer('6093ba0e2ab5775cfc01ed3e', personalOfferDocumentMock); + await usersService.addPersonalOffer('6093ba0e2ab5775cfc01ed3e', personalOfferDocumentMock); // Fail test if above expression doesn't throw anything. expect(true).toBe(false); } catch (e) { @@ -362,8 +362,8 @@ describe('UsersService', () => { describe('getStructureOwnersDetails', () => { const userDetailsMock: IUser[] = userDetails; it('should get Structure Owners Details', async () => { - jest.spyOn(service, 'getStructureOwnersDetails').mockResolvedValue(userDetails); - expect(await service.getStructureOwnersDetails('627b85aea0466f0f132e1599')).toEqual(userDetailsMock); + jest.spyOn(usersService, 'getStructureOwnersDetails').mockResolvedValue(userDetails); + expect(await usersService.getStructureOwnersDetails('627b85aea0466f0f132e1599')).toEqual(userDetailsMock); }); }); @@ -373,7 +373,7 @@ describe('UsersService', () => { mockUserModel.updateMany.mockReturnThis(); mockUserModel.exec.mockResolvedValueOnce([usersMockData[0]]); - await service.replaceEmployers(employersMockData[0], employersMockData[1]); + await usersService.replaceEmployers(employersMockData[0], employersMockData[1]); expect(spyer).toBeCalledTimes(1); }); @@ -425,10 +425,14 @@ describe('UsersService', () => { it('should updateUserProfile', async () => { const spyer = jest.spyOn(mockUserRegistrySearchService, 'update'); const spyerFindPopulate = jest - .spyOn(service, 'findPopulatedUserRegistryById') + .spyOn(usersService, 'findPopulatedUserRegistryById') .mockImplementationOnce(async () => userRegistryMockData); mockUserModel.exec.mockResolvedValueOnce(usersMockData[0]); - const result = await service.updateUserProfile(new Types.ObjectId('627b85aea0466f0f132e1599'), employer, job); + const result = await usersService.updateUserProfile( + new Types.ObjectId('627b85aea0466f0f132e1599'), + employer, + job + ); expect(spyer).toBeCalledTimes(1); expect(spyerFindPopulate).toBeCalledTimes(1); expect(result).toEqual(usersMockData[0]); @@ -436,7 +440,11 @@ describe('UsersService', () => { it('should not updateUserProfile', async () => { const spyer = jest.spyOn(mockUserRegistrySearchService, 'update'); mockUserModel.exec.mockResolvedValueOnce(null); - const result = await service.updateUserProfile(new Types.ObjectId('627b85aea0466f0f132e1599'), employer, job); + const result = await usersService.updateUserProfile( + new Types.ObjectId('627b85aea0466f0f132e1599'), + employer, + job + ); expect(spyer).toBeCalledTimes(0); expect(result).toEqual(null); }); @@ -451,10 +459,10 @@ describe('UsersService', () => { it('should updateUserJob', async () => { const spyer = jest.spyOn(mockUserRegistrySearchService, 'update'); const spyerFindPopulate = jest - .spyOn(service, 'findPopulatedUserRegistryById') + .spyOn(usersService, 'findPopulatedUserRegistryById') .mockImplementationOnce(async () => userRegistryMockData); mockUserModel.exec.mockResolvedValueOnce(usersMockData[0]); - const result = await service.updateUserJob(new Types.ObjectId('627b85aea0466f0f132e1599'), job); + const result = await usersService.updateUserJob(new Types.ObjectId('627b85aea0466f0f132e1599'), job); expect(spyer).toBeCalledTimes(1); expect(spyerFindPopulate).toBeCalledTimes(1); expect(result).toEqual(usersMockData[0]); @@ -462,7 +470,7 @@ describe('UsersService', () => { it('should not updateUserJob', async () => { const spyer = jest.spyOn(mockUserRegistrySearchService, 'update'); mockUserModel.exec.mockResolvedValueOnce(null); - const result = await service.updateUserJob(new Types.ObjectId('627b85aea0466f0f132e1599'), job); + const result = await usersService.updateUserJob(new Types.ObjectId('627b85aea0466f0f132e1599'), job); expect(spyer).toBeCalledTimes(0); expect(result).toEqual(null); }); @@ -477,10 +485,10 @@ describe('UsersService', () => { it('should updateUserEmployer', async () => { const spyer = jest.spyOn(mockUserRegistrySearchService, 'update'); const spyerFindPopulate = jest - .spyOn(service, 'findPopulatedUserRegistryById') + .spyOn(usersService, 'findPopulatedUserRegistryById') .mockImplementationOnce(async () => userRegistryMockData); mockUserModel.exec.mockResolvedValueOnce(usersMockData[0]); - const result = await service.updateUserEmployer(new Types.ObjectId('627b85aea0466f0f132e1599'), employer); + const result = await usersService.updateUserEmployer(new Types.ObjectId('627b85aea0466f0f132e1599'), employer); expect(spyer).toBeCalledTimes(1); expect(spyerFindPopulate).toBeCalledTimes(1); expect(result).toEqual(usersMockData[0]); @@ -488,7 +496,7 @@ describe('UsersService', () => { it('should not updateUserEmployer', async () => { const spyer = jest.spyOn(mockUserRegistrySearchService, 'update'); mockUserModel.exec.mockResolvedValueOnce(null); - const result = await service.updateUserEmployer(new Types.ObjectId('627b85aea0466f0f132e1599'), employer); + const result = await usersService.updateUserEmployer(new Types.ObjectId('627b85aea0466f0f132e1599'), employer); expect(spyer).toBeCalledTimes(0); expect(result).toEqual(null); }); @@ -500,9 +508,9 @@ describe('UsersService', () => { const detailsDto: UpdateDetailsDto = { name: 'Michel', surname: 'Chelmi', phone: '0601020304' }; mockUserModel.exec.mockResolvedValueOnce({ ...user, ...detailsDto }); const spyerFindPopulate = jest - .spyOn(service, 'findPopulatedUserRegistryById') + .spyOn(usersService, 'findPopulatedUserRegistryById') .mockImplementationOnce(async () => userRegistryMockData); - const updatedUser = await service.updateUserDetails('', { name: '', surname: '', phone: '' }); + const updatedUser = await usersService.updateUserDetails('', { name: '', surname: '', phone: '' }); expect(spyerFindPopulate).toBeCalledTimes(1); expect(updatedUser.name).toBe(detailsDto.name); expect(updatedUser.surname).toBe(detailsDto.surname); @@ -512,7 +520,7 @@ describe('UsersService', () => { mockUserModel.findByIdAndUpdate.mockReturnThis(); mockUserModel.exec.mockResolvedValueOnce(null); try { - await service.updateUserDetails('', { name: '', surname: '', phone: '' }); + await usersService.updateUserDetails('', { name: '', surname: '', phone: '' }); expect(true).toBe(false); } catch (error) { expect(error.message).toBe('User not found'); @@ -527,16 +535,16 @@ describe('UsersService', () => { const updatedDescription: DescriptionDto = { description: 'hello friend' }; mockUserModel.exec.mockResolvedValueOnce({ ...user, ...updatedDescription }); const spyerFindPopulate = jest - .spyOn(service, 'findPopulatedUserRegistryById') + .spyOn(usersService, 'findPopulatedUserRegistryById') .mockImplementationOnce(async () => userRegistryMockData); - const updatedUser = await service.updateDescription('', { description: '' }); + const updatedUser = await usersService.updateDescription('', { description: '' }); expect(spyerFindPopulate).toBeCalledTimes(1); expect(updatedUser.description).toBe(updatedDescription.description); }); it('should not found a user', async () => { mockUserModel.exec.mockResolvedValueOnce(null); try { - await service.updateDescription('', { description: '' }); + await usersService.updateDescription('', { description: '' }); expect(true).toBe(false); } catch (error) { expect(error.message).toBe('User not found'); @@ -549,14 +557,14 @@ describe('UsersService', () => { it('should call userModel.find if CNFS job found', async () => { mockJobsService.findByName.mockResolvedValueOnce(cnfsJobMock); const spyer = jest.spyOn(mockUserModel, 'find'); - await service.findAllCNFS(); + await usersService.findAllCNFS(); expect(spyer).toBeCalledTimes(1); }); it('should not call userModel.find if CNFS job not found', async () => { mockJobsService.findByName.mockResolvedValueOnce(null); const spyer = jest.spyOn(mockUserModel, 'find'); - await service.findAllCNFS(); + await usersService.findAllCNFS(); expect(spyer).toBeCalledTimes(0); }); });