Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • web-et-numerique/factory/pamn_plateforme-des-acteurs-de-la-mediation-numerique/pamn_server
1 result
Show changes
Showing
with 336 additions and 335 deletions
......@@ -40,10 +40,9 @@ import { QueryStructure } from './dto/query-structure.dto';
import { UpdateStructureDto } from './dto/update-structure.dto';
import { PhotonPoints } from './interfaces/photon-response.interface';
import { Structure, StructureDocument } from './schemas/structure.schema';
import { StructuresService } from './services/structures.service';
import { StructuresExportService } from './services/structures-export.service';
import { StructuresService } from './services/structures.service';
import { StructureFormatted } from './interfaces/structure-formatted.interface';
import { StructuresImportService } from './services/structures-import.service';
@ApiTags('structures')
@Controller('structures')
......@@ -53,7 +52,6 @@ export class StructuresController {
private readonly httpService: HttpService,
private readonly structureService: StructuresService,
private readonly structuresExportService: StructuresExportService,
private readonly structuresImportService: StructuresImportService,
private readonly userService: UsersService,
private readonly tempUserService: TempUserService,
private readonly categoriesService: CategoriesService,
......@@ -103,6 +101,7 @@ export class StructuresController {
query.query,
body ? body.filters : null,
null,
body?.onlyOffersWithAppointment || false,
body?.limit || null
);
}
......@@ -130,13 +129,6 @@ export class StructuresController {
return this.structureService.updateAllDenormalizedFields();
}
@Post('importDataGouv')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('admin')
public async importDataGouv(): Promise<void> {
return this.structuresImportService.importDataGouvStructures();
}
@Put('updateAfterOwnerVerify/:id')
public async updateAfterOwnerVerify(@Param('id') id: string): Promise<Structure> {
Logger.debug(`updateAfterOwnerVerify | structure ${id}`, StructuresController.name);
......
import { Body, Controller, Logger, Post, UseGuards } from '@nestjs/common';
import { Body, Controller, HttpException, HttpStatus, Logger, Post, UseGuards } from '@nestjs/common';
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { Roles } from '../users/decorators/roles.decorator';
......@@ -37,6 +37,12 @@ export class TclStopPointController {
})
@Post('/closest')
public getClosestStopPoints(@Body() pgisCoord: PgisCoord): Promise<TclStopPoint[]> {
if (pgisCoord.coordinates.includes(null)) {
throw new HttpException(
`Invalid empty coordinate: ${JSON.stringify(pgisCoord.coordinates)}`,
HttpStatus.BAD_REQUEST
);
}
return this.tclStopPointService.getClosestStopPoints(pgisCoord);
}
}
......@@ -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) {
......
......@@ -2,11 +2,15 @@ import { HttpModule } from '@nestjs/axios';
import { HttpStatus } from '@nestjs/common';
import { getModelToken } from '@nestjs/mongoose';
import { Test, TestingModule } from '@nestjs/testing';
import * as ejs from 'ejs';
import { MailerModule } from '../mailer/mailer.module';
import { MailerService } from '../mailer/mailer.service';
import { TempUserService } from './temp-user.service';
const ejsSpy = jest.spyOn(ejs, 'renderFile');
describe('TempUserService', () => {
let service: TempUserService;
let tempUserService: TempUserService;
const tempUserModelMock = {
create: jest.fn(),
......@@ -19,6 +23,24 @@ describe('TempUserService', () => {
updateOne: jest.fn(),
};
const mockMailService = {
send: jest.fn(),
getTemplateLocation: jest.fn(),
loadJsonConfig: jest.fn().mockReturnValue({ subject: 'subject' }),
config: {
templates: {
userAddedToStructure: {
ejs: 'userAddedToStructure.ejs',
json: 'userAddedToStructure.json',
},
tempUserRegistration: {
ejs: 'tempUserRegistration.ejs',
json: 'tempUserRegistration.json',
},
},
},
};
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [HttpModule, MailerModule],
......@@ -28,14 +50,15 @@ describe('TempUserService', () => {
provide: getModelToken('TempUser'),
useValue: tempUserModelMock,
},
{ provide: MailerService, useValue: mockMailService },
],
}).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 +66,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');
......@@ -52,23 +75,26 @@ describe('TempUserService', () => {
});
it('should create temporary user', async () => {
tempUserModelMock.findOne.mockReturnThis();
tempUserModelMock.exec.mockResolvedValueOnce(null).mockResolvedValueOnce(tmpUser);
tempUserModelMock.exec.mockResolvedValueOnce(null);
tempUserModelMock.create.mockResolvedValueOnce(tmpUser);
expect(await service.create(tmpUser, 'PIMMS Framboise')).toEqual(tmpUser);
tempUserModelMock.exec.mockResolvedValueOnce(tmpUser);
ejsSpy.mockResolvedValue('mock');
expect(await tempUserService.create(tmpUser, 'PIMMS Framboise')).toEqual(tmpUser);
expect(mockMailService.send).toHaveBeenCalled();
});
});
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 +104,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 +125,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 +133,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);
......
......@@ -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.');
......
......@@ -73,7 +73,7 @@ export class EmployerController {
// SEARCH
/**
* Init or reset search index for employere
* Init or reset search index for employer
* @returns {Employer[]}
*/
@Post('searchIndex')
......
......@@ -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.');
......
......@@ -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.');
......
......@@ -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);
});
});
......
......@@ -55,7 +55,8 @@ export class UsersRegistryController {
@Post('searchIndex')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('admin')
public async resetES(): Promise<IUserRegistry[]> {
public async resetES() {
this.logger.debug('reset ES UserRegistry');
return this.userRegistryService.initUserRegistryIndex();
}
}
......@@ -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);
});
});
......
......@@ -2,7 +2,7 @@ import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Types } from 'mongoose';
import { PersonalOfferDocument } from '../../personal-offers/schemas/personal-offer.schema';
import { Employer } from './employer.schema';
import { Job, JobDocument } from './job.schema';
import { JobDocument } from './job.schema';
import { UserRole } from '../enum/user-role.enum';
import { pendingStructuresLink } from '../interfaces/pendingStructure';
......@@ -60,10 +60,10 @@ export class User {
personalOffers: PersonalOfferDocument[];
@Prop({ type: Types.ObjectId, ref: 'Employer' })
employer: Employer;
employer?: Employer;
@Prop({ type: Types.ObjectId, ref: 'Job' })
job: JobDocument;
job?: JobDocument;
@Prop({ required: false })
withAppointment?: boolean;
......@@ -73,6 +73,19 @@ export class User {
@Prop({ default: null })
lastLoginDate: Date;
// Document methods
// static because object method would need to create a constructor and get an actual User instance (cf. https://stackoverflow.com/a/42899705 )
// Get if owner can have appointment
static getWithAppointment(user: User) {
if (user.job && !user.job.name) {
throw new Error(`job not populated for user ${user.surname} : ${user.job}`);
}
// Also check user has a job with personnalOffer (user may have changed his job after choosing withAppointment)
// and also check if user has personalOffers (otherwise they can't have appointment)
return user.withAppointment && user.job?.hasPersonalOffer && user.personalOffers?.length;
}
}
export const UserSchema = SchemaFactory.createForClass(User);
......
......@@ -18,22 +18,22 @@ const employers = [
} as EmployerDocument,
{
_id: new Types.ObjectId('6231aefe76598527c8d0b5bd'),
name: 'CAF',
name: 'CGI',
validated: true,
} as EmployerDocument,
{
_id: new Types.ObjectId('6231aefe76598527c8d0b5be'),
name: 'CARSAT',
name: 'Decathlon',
validated: true,
} as EmployerDocument,
{
_id: new Types.ObjectId('6231aefe76598527c8d0b5bf'),
name: 'CPAM',
name: 'Apollo',
validated: true,
} 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 () => {
......@@ -63,37 +63,37 @@ describe('EmployerSearchService Search cases', () => {
// await new Promise((r) => setTimeout(r, 2000));
// }, 10000);
it('should find CARSAT', async () => {
const res = await service.search('CARSAT');
expect(res[0].name).toBe('CARSAT');
it('should find Metro', async () => {
const res = await employerSearchService.search('Metro');
expect(res[0].name).toBe('Metro');
expect(res.length).toBe(1);
});
it('should find CAF', async () => {
const res = await service.search('CAF');
expect(res[0].name).toBe('CAF');
it('should find Sopra', async () => {
const res = await employerSearchService.search('Sopra');
expect(res[0].name).toBe('Sopra');
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('Metro');
const res = await employerSearchService.update(
resCaf[0] as EmployerDocument,
new Types.ObjectId('6231aefe76598527c8d0b5bd').toHexString()
new Types.ObjectId('6231aefe76598527c8d0b5ba').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('Metro');
const res = await employerSearchService.deleteIndex(
resCaf[0] as EmployerDocument,
new Types.ObjectId('6231aefe76598527c8d0b5bd').toHexString()
new Types.ObjectId('6231aefe76598527c8d0b5ba').toHexString()
);
expect(res).toBeTruthy();
});
......
This diff is collapsed.
......@@ -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);
......
import { ElasticsearchService } from '@nestjs/elasticsearch';
import { Test, TestingModule } from '@nestjs/testing';
import { multipleUsers } from '../../../test/mock/data/users.mock.data';
import { ConfigurationModule } from '../../configuration/configuration.module';
......@@ -6,7 +7,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,51 +15,53 @@ 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);
expect(res).toBeTruthy();
const mockDelete = jest.fn();
jest.spyOn(ElasticsearchService.prototype, 'delete').mockImplementation(mockDelete);
const resAdm = await userRegistrySearchService.search('adm');
await userRegistrySearchService.deleteIndex(resAdm[0] as IUserRegistry);
expect(mockDelete).toBeCalled();
});
});
});