Skip to content

Commit e85179f

Browse files
Mise à jour du contrôleur d'identités
1 parent 1054aa8 commit e85179f

File tree

2 files changed

+84
-35
lines changed

2 files changed

+84
-35
lines changed

src/_common/tests/mock.service.ts

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* Enhances createMockService to handle an arbitrary number of call behaviors dynamically.
3+
* @param service The service class to mock.
4+
* @param methodStubs An object where keys are method names and values are arrays of behaviors for those methods.
5+
* @returns A mock service instance with dynamically stubbed methods.
6+
*/
7+
export function createMockService<T>(service: new (...args: any[]) => T, methodStubs: Record<string, any[] | any>): T {
8+
const mockService = {};
9+
10+
Object.entries(methodStubs).forEach(([method, stubValueOrArray]) => {
11+
const stubValues = Array.isArray(stubValueOrArray) ? stubValueOrArray : [stubValueOrArray];
12+
const methodMock = jest.fn();
13+
14+
stubValues.forEach((stubValue) => {
15+
methodMock.mockImplementationOnce((...args) => {
16+
if (typeof stubValue === 'function') {
17+
return stubValue(...args);
18+
} else if (stubValue instanceof Error) {
19+
throw stubValue;
20+
} else {
21+
return stubValue;
22+
}
23+
});
24+
});
25+
26+
mockService[method] = methodMock;
27+
});
28+
29+
return mockService as T;
30+
}

src/management/identities/identities.controller.spec.ts

Lines changed: 54 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,18 @@ import { FilterOptions } from '@streamkits/nestjs_module_scrud';
22
import { Test, TestingModule } from '@nestjs/testing';
33
import { IdentitiesController } from './identities.controller';
44
import { IdentitiesService } from './identities.service';
5-
import { Identities, IdentitiesSchema } from './_schemas/identities.schema';
5+
import { Identities, IdentitiesDocument, IdentitiesSchema } from './_schemas/identities.schema';
66
import { HttpStatus } from '@nestjs/common';
7-
import { Model, Types } from 'mongoose';
7+
import { Model, ModifyResult, Query, Types } from 'mongoose';
88
import { Response } from 'express';
99
import { getModelToken } from '@nestjs/mongoose';
1010
import { IdentitiesDtoStub } from './_stubs/identities.dto.stub';
1111
import { IdentitiesValidationService } from './validations/identities.validation.service';
1212
import { IdentitiesValidationModule } from './validations/identities.validation.module';
1313
import { MockResponse, createResponse } from 'node-mocks-http';
14-
import { ValidationSchemaException } from '~/_common/errors/ValidationException';
1514
import { MongoDbTestInstance } from '~/_common/tests/mongodb.test.instance';
15+
import { IdentityState } from './_enums/states.enum';
16+
import { createMockService } from '~/_common/tests/mock.service';
1617

1718
describe('IdentitiesController', () => {
1819
let controller: IdentitiesController;
@@ -35,20 +36,61 @@ describe('IdentitiesController', () => {
3536
mongoDbTestInstance = new MongoDbTestInstance();
3637
await mongoDbTestInstance.start();
3738
identitiesModel = await mongoDbTestInstance.getModel<Identities>(Identities.name, IdentitiesSchema);
39+
_id = new Types.ObjectId();
40+
41+
// service = createMockService<IdentitiesService>(IdentitiesService, {
42+
// create: [{ ...identitiesCreated }, { ...identitiesAccepted }],
43+
// findAndCount: [{ data: [identitiesWithId], total: 1 }],
44+
// findOne: [{ ...identitiesWithId }],
45+
// update: [{ ...identitiesWithId }],
46+
// delete: [{ ...identitiesWithId }],
47+
// });
48+
49+
service = createMockService<IdentitiesService>(IdentitiesService, {
50+
create: [
51+
// First call returns a newly created identity with a status of CREATED
52+
Promise.resolve({ ...IdentitiesDtoStub(), _id, state: IdentityState.TO_VALIDATE }),
53+
// Second call simulates a scenario where creation leads to ACCEPTED status due to validations
54+
Promise.resolve({ ...IdentitiesDtoStub(), _id, state: IdentityState.TO_COMPLETE }),
55+
],
56+
findAndCount: [
57+
// Successful search, returns an array of identities and a total count
58+
Promise.resolve({ data: [{ ...IdentitiesDtoStub(), _id }], total: 1 }),
59+
// Simulate a failure in searching identities
60+
Promise.reject(new Error('Error')),
61+
],
62+
findOne: [
63+
// Successfully finds an identity
64+
Promise.resolve({ ...IdentitiesDtoStub(), _id }),
65+
// Simulates an error when finding an identity
66+
Promise.reject(new Error('Error')),
67+
],
68+
update: [
69+
// Successfully updates an identity
70+
Promise.resolve({ ...IdentitiesDtoStub(), _id }),
71+
// Simulates an error in updating an identity
72+
Promise.reject(new Error('Error')),
73+
],
74+
delete: [
75+
// Successfully deletes an identity
76+
Promise.resolve({ ...IdentitiesDtoStub(), _id }),
77+
// Simulates an error in deleting an identity
78+
Promise.reject(new Error('Error')),
79+
],
80+
});
3881

3982
const module: TestingModule = await Test.createTestingModule({
4083
controllers: [IdentitiesController],
4184
providers: [
42-
IdentitiesService,
85+
{ provide: IdentitiesService, useValue: service },
4386
{ provide: getModelToken(Identities.name), useValue: identitiesModel },
4487
IdentitiesValidationService,
4588
],
4689
imports: [IdentitiesValidationModule],
4790
}).compile();
4891

4992
controller = module.get<IdentitiesController>(IdentitiesController);
50-
service = module.get<IdentitiesService>(IdentitiesService);
51-
_id = new Types.ObjectId();
93+
//service = module.get<IdentitiesService>(IdentitiesService);
5294
}, 1200000);
5395

5496
beforeEach(() => {
@@ -65,28 +107,15 @@ describe('IdentitiesController', () => {
65107
});
66108

67109
describe('create', () => {
68-
it('should create an identity', async () => {
69-
jest.spyOn(service, 'create').mockResolvedValue(IdentitiesDtoStub() as Identities);
70-
110+
it('should create an identity with no errors', async () => {
71111
const createIdentity = await controller.create(response, IdentitiesDtoStub());
72-
expect(createIdentity.statusCode).toMatch(new RegExp(`(${HttpStatus.CREATED})|(${HttpStatus.ACCEPTED})`));
112+
expect(createIdentity.statusCode).toBe(HttpStatus.CREATED);
73113
});
74114

75-
// it('should handle ValidationSchemaException by returning the appropriate status code and message', async () => {
76-
// jest.spyOn(service, 'create').mockRejectedValue(
77-
// new ValidationSchemaException({
78-
// message: 'Schema validation failed',
79-
// validations: { field: 'error' },
80-
// statusCode: HttpStatus.BAD_REQUEST,
81-
// }),
82-
// );
83-
84-
// const response = createResponse();
85-
// const identity = IdentitiesDtoStub();
86-
// const createIdentity = await controller.create(response, identity);
87-
// expect(createIdentity.statusCode).toBe(HttpStatus.ACCEPTED);
88-
// expect(response).toHaveProperty('greger');
89-
// });
115+
it('should create an identity with validations', async () => {
116+
const createIdentity = await controller.create(response, IdentitiesDtoStub());
117+
expect(createIdentity.statusCode).toBe(HttpStatus.ACCEPTED);
118+
});
90119
});
91120

92121
describe('search', () => {
@@ -96,7 +125,6 @@ describe('IdentitiesController', () => {
96125
});
97126

98127
it('should throw an error when searching identities', async () => {
99-
jest.spyOn(service, 'findAndCount').mockRejectedValueOnce(new Error('Error'));
100128
try {
101129
await controller.search(response, {}, searchFilterOptions);
102130
} catch (error) {
@@ -107,14 +135,11 @@ describe('IdentitiesController', () => {
107135

108136
describe('read', () => {
109137
it('should find an identity', async () => {
110-
const newIdentity = await service.create<Identities>(IdentitiesDtoStub());
111-
const _id = newIdentity.id;
112138
const findIdentity = await controller.read(_id, response);
113139
expect(findIdentity.statusCode).toBe(HttpStatus.OK);
114140
});
115141

116142
it('should throw an error when finding an identity', async () => {
117-
jest.spyOn(service, 'findOne').mockRejectedValueOnce(new Error('Error'));
118143
try {
119144
await controller.read(_id, response);
120145
} catch (error) {
@@ -125,14 +150,11 @@ describe('IdentitiesController', () => {
125150

126151
describe('update', () => {
127152
it('should update an identity', async () => {
128-
const newIdentity = await service.create<Identities>(IdentitiesDtoStub());
129-
const _id = newIdentity.id;
130153
const updateIdentity = await controller.update(_id, IdentitiesDtoStub(), response);
131154
expect(updateIdentity.statusCode).toBe(HttpStatus.OK);
132155
});
133156

134157
it('should throw an error when updating an identity', async () => {
135-
jest.spyOn(service, 'update').mockRejectedValueOnce(new Error('Error'));
136158
try {
137159
await controller.update(_id, IdentitiesDtoStub(), response);
138160
} catch (error) {
@@ -143,14 +165,11 @@ describe('IdentitiesController', () => {
143165

144166
describe('delete', () => {
145167
it('should delete an identity', async () => {
146-
const newIdentity = await service.create<Identities>(IdentitiesDtoStub());
147-
const _id = newIdentity.id;
148168
const deleteIdentity = await controller.remove(_id, response);
149169
expect(deleteIdentity.statusCode).toBe(HttpStatus.OK);
150170
});
151171

152172
it('should throw an error when deleting an identity', async () => {
153-
jest.spyOn(service, 'delete').mockRejectedValueOnce(new Error('Error'));
154173
try {
155174
await controller.remove(_id, response);
156175
} catch (error) {

0 commit comments

Comments
 (0)