From 6b6d4bd12e21b6769474a0477e6675d55b8974a5 Mon Sep 17 00:00:00 2001
From: Hugo SUBTIL <ext.sopra.husubtil@grandlyon.com>
Date: Fri, 26 Mar 2021 14:03:36 +0100
Subject: [PATCH] fix: unitary test + update test coverage config

---
 package.json                               |  2 +-
 src/admin/admin.controller.spec.ts         | 22 ++++++++++
 src/configuration/configuration.service.ts |  1 -
 src/posts/posts.controller.spec.ts         |  5 +++
 src/posts/posts.service.spec.ts            |  3 ++
 src/tcl/tclStopPoint.service.spec.ts       | 12 +++++-
 src/users/users.controller.spec.ts         | 14 +++++++
 src/users/users.service.spec.ts            | 48 +++++++++++++++++++---
 src/users/users.service.ts                 |  4 +-
 test/jest-e2e.json                         |  3 +-
 test/jest.json                             |  9 ++++
 11 files changed, 112 insertions(+), 11 deletions(-)
 create mode 100644 test/jest.json

diff --git a/package.json b/package.json
index e0d0bd9bb..90ae0fddd 100644
--- a/package.json
+++ b/package.json
@@ -17,7 +17,7 @@
     "init-db": "node ./scripts/init-db.js",
     "test": "jest",
     "test:watch": "jest --watch",
-    "test:cov": "jest --coverage",
+    "test:cov": "jest --config ./test/jest.json --coverage",
     "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
     "test:e2e": "jest --config ./test/jest-e2e.json"
   },
diff --git a/src/admin/admin.controller.spec.ts b/src/admin/admin.controller.spec.ts
index 0b8ca9028..65e9b88e4 100644
--- a/src/admin/admin.controller.spec.ts
+++ b/src/admin/admin.controller.spec.ts
@@ -1,4 +1,12 @@
+import { HttpModule } from '@nestjs/common';
+import { getModelToken } from '@nestjs/mongoose';
 import { Test, TestingModule } from '@nestjs/testing';
+import { ConfigurationModule } from '../configuration/configuration.module';
+import { MailerService } from '../mailer/mailer.service';
+import { Structure } from '../structures/schemas/structure.schema';
+import { StructuresService } from '../structures/services/structures.service';
+import { User } from '../users/schemas/user.schema';
+import { UsersService } from '../users/users.service';
 import { AdminController } from './admin.controller';
 
 describe('AdminController', () => {
@@ -6,6 +14,20 @@ describe('AdminController', () => {
 
   beforeEach(async () => {
     const module: TestingModule = await Test.createTestingModule({
+      imports: [ConfigurationModule, HttpModule],
+      providers: [
+        UsersService,
+        StructuresService,
+        MailerService,
+        {
+          provide: getModelToken('User'),
+          useValue: User,
+        },
+        {
+          provide: getModelToken('Structure'),
+          useValue: Structure,
+        },
+      ],
       controllers: [AdminController],
     }).compile();
 
diff --git a/src/configuration/configuration.service.ts b/src/configuration/configuration.service.ts
index 9af45d3b2..e7a723f37 100644
--- a/src/configuration/configuration.service.ts
+++ b/src/configuration/configuration.service.ts
@@ -18,7 +18,6 @@ export class ConfigurationService {
       Logger.log('App started with dev conf', 'ConfigurationService');
     } else {
       this._config = config;
-      Logger.log('App started with local conf', 'ConfigurationService');
     }
     dotenv.config();
   }
diff --git a/src/posts/posts.controller.spec.ts b/src/posts/posts.controller.spec.ts
index 7784335f5..0c5120801 100644
--- a/src/posts/posts.controller.spec.ts
+++ b/src/posts/posts.controller.spec.ts
@@ -1,11 +1,16 @@
+import { HttpModule } from '@nestjs/common';
 import { Test, TestingModule } from '@nestjs/testing';
+import { ConfigurationModule } from '../configuration/configuration.module';
 import { PostsController } from './posts.controller';
+import { PostsService } from './posts.service';
 
 describe('PostsController', () => {
   let controller: PostsController;
 
   beforeEach(async () => {
     const module: TestingModule = await Test.createTestingModule({
+      imports: [ConfigurationModule, HttpModule],
+      providers: [PostsService],
       controllers: [PostsController],
     }).compile();
 
diff --git a/src/posts/posts.service.spec.ts b/src/posts/posts.service.spec.ts
index e15215844..5b01e5556 100644
--- a/src/posts/posts.service.spec.ts
+++ b/src/posts/posts.service.spec.ts
@@ -1,4 +1,6 @@
+import { HttpModule } from '@nestjs/common';
 import { Test, TestingModule } from '@nestjs/testing';
+import { ConfigurationModule } from '../configuration/configuration.module';
 import { PostsService } from './posts.service';
 
 describe('PostsService', () => {
@@ -6,6 +8,7 @@ describe('PostsService', () => {
 
   beforeEach(async () => {
     const module: TestingModule = await Test.createTestingModule({
+      imports: [ConfigurationModule, HttpModule],
       providers: [PostsService],
     }).compile();
 
diff --git a/src/tcl/tclStopPoint.service.spec.ts b/src/tcl/tclStopPoint.service.spec.ts
index 4958e5931..2c6d4220f 100644
--- a/src/tcl/tclStopPoint.service.spec.ts
+++ b/src/tcl/tclStopPoint.service.spec.ts
@@ -1,4 +1,7 @@
+import { HttpModule } from '@nestjs/common';
+import { getModelToken } from '@nestjs/mongoose';
 import { Test, TestingModule } from '@nestjs/testing';
+import { TclStopPoint } from './tclStopPoint.schema';
 import { TclStopPointService } from './tclStopPoint.service';
 
 describe('TclService', () => {
@@ -6,7 +9,14 @@ describe('TclService', () => {
 
   beforeEach(async () => {
     const module: TestingModule = await Test.createTestingModule({
-      providers: [TclStopPointService],
+      imports: [HttpModule],
+      providers: [
+        TclStopPointService,
+        {
+          provide: getModelToken('TclStopPoint'),
+          useValue: TclStopPoint,
+        },
+      ],
     }).compile();
 
     service = module.get<TclStopPointService>(TclStopPointService);
diff --git a/src/users/users.controller.spec.ts b/src/users/users.controller.spec.ts
index 7dd57ee72..584333cf2 100644
--- a/src/users/users.controller.spec.ts
+++ b/src/users/users.controller.spec.ts
@@ -3,6 +3,10 @@ import { getModelToken } from '@nestjs/mongoose';
 import { Test, TestingModule } from '@nestjs/testing';
 import { ConfigurationModule } from '../configuration/configuration.module';
 import { MailerService } from '../mailer/mailer.service';
+import { Structure } from '../structures/schemas/structure.schema';
+import { StructuresService } from '../structures/services/structures.service';
+import { TempUser } from '../temp-user/temp-user.schema';
+import { TempUserService } from '../temp-user/temp-user.service';
 import { User } from './schemas/user.schema';
 import { UsersController } from './users.controller';
 import { UsersService } from './users.service';
@@ -15,7 +19,17 @@ describe('UsersController', () => {
       imports: [ConfigurationModule, HttpModule],
       providers: [
         UsersService,
+        StructuresService,
         MailerService,
+        TempUserService,
+        {
+          provide: getModelToken('TempUser'),
+          useValue: TempUser,
+        },
+        {
+          provide: getModelToken('Structure'),
+          useValue: Structure,
+        },
         {
           provide: getModelToken('User'),
           useValue: User,
diff --git a/src/users/users.service.spec.ts b/src/users/users.service.spec.ts
index 01f5207c7..668890e12 100644
--- a/src/users/users.service.spec.ts
+++ b/src/users/users.service.spec.ts
@@ -48,15 +48,32 @@ describe('UsersService', () => {
         changeEmailToken: '',
         resetPasswordToken: null,
         structuresLink: [],
+        structureOutdatedMailSent: [],
+        pendingStructuresLink: [],
+        name: 'Jacques',
+        surname: 'Dupont',
+        phone: '06 06 06 06 06',
       };
-      const userDto: CreateUserDto = { email: 'jacques.dupont@mii.com', password: 'test1A!!' }; //NOSONAR
+      const userDto: CreateUserDto = {
+        email: 'jacques.dupont@mii.com',
+        password: 'test1A!!',
+        name: 'Jacques',
+        surname: 'Dupont',
+        phone: '06 06 06 06 06',
+      }; //NOSONAR
       jest.spyOn(service, 'create').mockImplementation(async (): Promise<User> => result);
       expect(await service.create(userDto)).toBe(result);
     });
 
     it('User should not be created, already exist', async () => {
       const result = new HttpException('User already exists', HttpStatus.BAD_REQUEST);
-      const userDto: CreateUserDto = { email: 'jacques.dupont@mii.com', password: 'test1A!!' }; //NOSONAR
+      const userDto: CreateUserDto = {
+        email: 'jacques.dupont@mii.com',
+        password: 'test1A!!',
+        name: 'Jacques',
+        surname: 'Dupont',
+        phone: '06 06 06 06 06',
+      }; //NOSONAR
       jest.spyOn(service, 'create').mockImplementation(async (): Promise<any> => result);
       expect(await service.create(userDto)).toBe(result);
     });
@@ -66,7 +83,13 @@ describe('UsersService', () => {
         'Weak password, it must contain ne lowercase alphabetical character, one uppercase alphabetical character, one numeric character, one special character and be eight characters or longer',
         HttpStatus.UNPROCESSABLE_ENTITY
       );
-      const userDto: CreateUserDto = { email: 'jacques.dupont@mii.com', password: 'test' }; //NOSONAR
+      const userDto: CreateUserDto = {
+        email: 'jacques.dupont@mii.com',
+        password: 'test',
+        name: 'Jacques',
+        surname: 'Dupont',
+        phone: '06 06 06 06 06',
+      }; //NOSONAR
       jest.spyOn(service, 'create').mockImplementation(async (): Promise<any> => result);
       expect(await service.create(userDto)).toBe(result);
     });
@@ -85,6 +108,11 @@ describe('UsersService', () => {
         changeEmailToken: '',
         resetPasswordToken: null,
         structuresLink: [],
+        pendingStructuresLink: [],
+        structureOutdatedMailSent: [],
+        name: 'Jacques',
+        surname: 'Dupont',
+        phone: '06 06 06 06 06',
       };
       const loginDto: LoginDto = { email: 'jacques.dupont@mii.com', password: 'test1A!!' }; //NOSONAR
       jest.spyOn(service, 'findByLogin').mockImplementation(async (): Promise<User> => result);
@@ -143,6 +171,11 @@ describe('UsersService', () => {
         newEmail: 'test.dupont@mail.com',
         resetPasswordToken: '',
         structuresLink: [],
+        pendingStructuresLink: [],
+        structureOutdatedMailSent: [],
+        name: 'Jacques',
+        surname: 'Dupont',
+        phone: '06 06 06 06 06',
         changeEmailToken:
           '9bb3542bdc5ca8801ad4cee00403c1052bc95dee768dcbb65b1f719870578ed79f71f52fdc3e6bf02fd200a72b8b6f56fc26950df30c8cd7e427a485f80181b9',
       };
@@ -173,6 +206,11 @@ describe('UsersService', () => {
         resetPasswordToken: '',
         changeEmailToken: '',
         structuresLink: [],
+        pendingStructuresLink: [],
+        structureOutdatedMailSent: [],
+        name: 'Jacques',
+        surname: 'Dupont',
+        phone: '06 06 06 06 06',
       };
       const token =
         '9bb3542bdc5ca8801ad4cee00403c1052bc95dee768dcbb65b1f719870578ed79f71f52fdc3e6bf02fd200a72b8b6f56fc26950df30c8cd7e427a485f80181b9'; //NOSONAR
@@ -241,13 +279,13 @@ describe('UsersService', () => {
     it('should return structureLink tab ', async () => {
       const result = [53];
       jest.spyOn(service, 'updateStructureLinked').mockImplementation(async (): Promise<any> => result);
-      expect(await service.updateStructureLinked('test@mii.com', 53)).toBe(result);
+      expect(await service.updateStructureLinked('test@mii.com', '6001a37716b08100062e4160')).toBe(result);
     });
 
     it('should return invalid User ', async () => {
       const result = new HttpException('Invalid user', HttpStatus.NOT_FOUND);
       jest.spyOn(service, 'updateStructureLinked').mockImplementation(async (): Promise<any> => result);
-      expect(await service.updateStructureLinked('test@mii.com', 53)).toBe(result);
+      expect(await service.updateStructureLinked('test@mii.com', '6001a37716b08100062e4160')).toBe(result);
     });
   });
 });
diff --git a/src/users/users.service.ts b/src/users/users.service.ts
index c7806f64e..7b6915537 100644
--- a/src/users/users.service.ts
+++ b/src/users/users.service.ts
@@ -21,7 +21,7 @@ export class UsersService {
    * Create a user account
    * @param createUserDto CreateUserDto
    */
-  public async create(createUserDto: CreateUserDto): Promise<User> {
+  public async create(createUserDto: CreateUserDto): Promise<User | HttpStatus> {
     const userInDb = await this.findOne(createUserDto.email);
     if (userInDb) {
       throw new HttpException('User already exists', HttpStatus.BAD_REQUEST);
@@ -198,7 +198,7 @@ export class UsersService {
    * @param userId string
    * @param token string
    */
-  public async validateUser(userId: string, token: string): Promise<User> {
+  public async validateUser(userId: string, token: string): Promise<User | HttpException> {
     const user = await this.findById(userId);
     if (user && user.validationToken === token) {
       user.validationToken = null;
diff --git a/test/jest-e2e.json b/test/jest-e2e.json
index e9d912f3e..dece89cce 100644
--- a/test/jest-e2e.json
+++ b/test/jest-e2e.json
@@ -5,5 +5,6 @@
   "testRegex": ".e2e-spec.ts$",
   "transform": {
     "^.+\\.(t|j)s$": "ts-jest"
-  }
+  },
+  "collectCoverage": true
 }
diff --git a/test/jest.json b/test/jest.json
new file mode 100644
index 000000000..b49b407c3
--- /dev/null
+++ b/test/jest.json
@@ -0,0 +1,9 @@
+{
+  "moduleFileExtensions": ["js", "json", "ts"],
+  "rootDir": "../src",
+  "testEnvironment": "node",
+  "transform": {
+    "^.+\\.(t|j)s$": "ts-jest"
+  },
+  "collectCoverage": true
+}
-- 
GitLab