From c3a10775ea6c32135ec170f00ab52636cd848854 Mon Sep 17 00:00:00 2001 From: Yavor Stoychev Date: Tue, 20 Feb 2024 13:14:22 +0200 Subject: [PATCH] fix(code-coverage): bumping code coverage --- .../src/api/auth/interfaces/auth.ts | 1 + .../api/auth/routes/register.route.test.ts | 25 ++ .../api/auth/services/auth.service.spec.ts | 86 +++++++ .../api/auth/services/auth0.service.spec.ts | 213 ++++++++++++++++++ .../src/api/auth/services/auth0.service.ts | 38 ++-- .../repositories/todos.repository.test.ts | 22 +- .../repositories/users.repository.test.ts | 28 ++- express-pg-auth0/src/app.test.ts | 2 +- .../src/utils/environment.test.ts | 47 +++- express-pg-auth0/src/utils/environment.ts | 1 - .../api/auth/services/auth0.service.spec.ts | 2 +- .../api/auth/services/auth.service.spec.ts | 6 +- .../api/auth/services/auth.service.spec.ts | 2 +- .../api/auth/services/auth0.service.spec.ts | 20 +- .../src/api/todos/todos.service.spec.ts | 2 +- .../api/auth/services/auth.service.spec.ts | 6 +- .../src/api/todos/todos.service.spec.ts | 4 +- .../src/api/todos/todos.service.spec.ts | 4 +- .../auth0/services/auth0.service.spec.ts | 2 +- .../mongodb/jwt/services/auth.service.spec.ts | 6 +- .../pg/auth0/services/auth.service.spec.ts | 2 +- .../pg/auth0/services/auth0.service.spec.ts | 14 +- .../pg/jwt/services/auth.service.spec.ts | 6 +- 23 files changed, 445 insertions(+), 94 deletions(-) create mode 100644 express-pg-auth0/src/api/auth/routes/register.route.test.ts create mode 100644 express-pg-auth0/src/api/auth/services/auth.service.spec.ts create mode 100644 express-pg-auth0/src/api/auth/services/auth0.service.spec.ts diff --git a/express-pg-auth0/src/api/auth/interfaces/auth.ts b/express-pg-auth0/src/api/auth/interfaces/auth.ts index 1123a9de..955299dc 100644 --- a/express-pg-auth0/src/api/auth/interfaces/auth.ts +++ b/express-pg-auth0/src/api/auth/interfaces/auth.ts @@ -19,4 +19,5 @@ export type Auth0User = { updated_at: string; user_id: string; user_metadata: Record; + blocked: boolean; }; \ No newline at end of file diff --git a/express-pg-auth0/src/api/auth/routes/register.route.test.ts b/express-pg-auth0/src/api/auth/routes/register.route.test.ts new file mode 100644 index 00000000..865c5c83 --- /dev/null +++ b/express-pg-auth0/src/api/auth/routes/register.route.test.ts @@ -0,0 +1,25 @@ +import { registerRoute as route } from './register.route'; + +describe('route', () => { + it('should be defined', () => { + expect(route).toBeDefined(); + }); + + describe('handler', () => { + const authService = { register: jest.fn(() => ({ user: 'user' })) }; + const req = { + auth: { payload: { sub: '1' } }, + + body: { name: 'Name' }, + services: { authService }, + }; + const send = jest.fn(); + const status = jest.fn(() => ({ send })); + const res = { send, status }; + + it('should call AuthService#register', () => { + route.handler(req as never, res as never, jest.fn()); + expect(authService.register).toHaveBeenCalledWith({ name: 'Name' }); + }); + }); +}); diff --git a/express-pg-auth0/src/api/auth/services/auth.service.spec.ts b/express-pg-auth0/src/api/auth/services/auth.service.spec.ts new file mode 100644 index 00000000..1012a774 --- /dev/null +++ b/express-pg-auth0/src/api/auth/services/auth.service.spec.ts @@ -0,0 +1,86 @@ +import { User } from '@api/users'; +import { AuthService } from './auth.service'; +import { Auth0User, Credentials } from '../interfaces'; + +const userCreds: Credentials = { + email: 'new-email@example.com', + password: 'very-secret', +}; + +const registeredUser: User = { + id: '1', + createdAt: Date.now().toString(), + updatedAt: Date.now().toString(), + email: userCreds.email, + password: 'very-secret', + userId: '1', +}; + +const auth0User: Auth0User = { + blocked: false, + created_at: Date.now().toString(), + email: userCreds.email, + email_verified: true, + identities: [], + name: 'userName', + nickname: 'userNickname', + picture: '', + updated_at: Date.now().toString(), + user_id: '1', + user_metadata: {}, +}; + +describe('AuthService', () => { + const logger = { + warn: jest.fn(), + error: jest.fn(), + } as any; + + const auth0Service = { + createUser: jest.fn(), + deleteUser: jest.fn(), + updateUserMetadata: jest.fn(), + } as any; + + const usersRepository = { + insertOne: jest.fn(), + } as any; + + const authService = new AuthService(logger, auth0Service, usersRepository); + + afterEach(() => { + jest.clearAllMocks(); + }); + + describe('register', () => { + it('when the email is not registered should register the user', async () => { + const createdUser = { ...registeredUser, ...userCreds }; + auth0Service.createUser.mockResolvedValueOnce(auth0User); + usersRepository.insertOne.mockResolvedValueOnce(createdUser); + auth0Service.updateUserMetadata.mockResolvedValueOnce(auth0User as any); + + const user = await authService.register(userCreds); + + expect(auth0Service.updateUserMetadata).toHaveBeenCalledWith(auth0User.user_id, { + id: createdUser.id + }); + + expect(user).toEqual({ + email: userCreds.email, + userId: auth0User.user_id, + }); + }); + + it('throws error when creating a user in the database fails', async () => { + auth0Service.createUser.mockResolvedValueOnce(auth0User); + usersRepository.insertOne.mockRejectedValueOnce({ error: 'error' }); + auth0Service.deleteUser.mockResolvedValueOnce(auth0User as any); + + await expect(authService.register(userCreds)).rejects.toThrow(); + + expect(logger.warn).toHaveBeenCalledWith('Creating a user in the database failed. Proceeding with deleting it in Auth0.'); + expect(auth0Service.deleteUser).toHaveBeenCalledWith(auth0User.user_id); + + }); + }); +}); diff --git a/express-pg-auth0/src/api/auth/services/auth0.service.spec.ts b/express-pg-auth0/src/api/auth/services/auth0.service.spec.ts new file mode 100644 index 00000000..4d35d397 --- /dev/null +++ b/express-pg-auth0/src/api/auth/services/auth0.service.spec.ts @@ -0,0 +1,213 @@ +import { AxiosStatic } from 'axios'; +import { Auth0User, Credentials } from '../interfaces'; +import { Auth0Service } from './auth0.service'; +import { Logger } from 'pino'; +import { Environment } from '@utils/environment'; + +const userCreds: Credentials = { + email: 'new-email@example.com', + password: 'very-secret', +}; + +const auth0User: Auth0User = { + blocked: false, + created_at: Date.now().toString(), + email: userCreds.email, + email_verified: true, + identities: [], + name: 'userName', + nickname: 'userNickname', + picture: '', + updated_at: Date.now().toString(), + user_id: '1', + user_metadata: {}, +}; + +describe('Auth0Service', () => { + let auth0Service: Auth0Service; + let axios: AxiosStatic; + let logger: Logger; + let env: Environment; + + beforeAll(() => { + logger = { error: jest.fn() } as any; + axios = { + post: jest.fn(), + patch: jest.fn(), + get: jest.fn(), + delete: jest.fn(), + } as any; + env = {} as any; + }); + + afterEach(() => { + jest.clearAllMocks(); + }); + + describe('createUser', () => { + beforeEach(() => { + auth0Service = new Auth0Service(logger, axios, env); + jest + .spyOn(auth0Service, 'getAuth0AccessToken') + .mockResolvedValue('token'); + }); + + it('when the email is not registered should register the user', async () => { + jest + .spyOn(auth0Service, 'searchUsersByEmail') + .mockResolvedValueOnce([] as unknown as Auth0User); + jest + .spyOn(axios, 'post') + .mockResolvedValueOnce(Promise.resolve({ data: auth0User })); + + const user = await auth0Service.createUser( + userCreds.email, + userCreds.password + ); + + expect(user).toEqual(auth0User); + }); + + it('throws error when user is already registered', async () => { + jest + .spyOn(auth0Service, 'searchUsersByEmail') + .mockResolvedValueOnce([auth0User] as unknown as Auth0User); + + await expect( + auth0Service.createUser(userCreds.email, userCreds.password) + ).rejects.toThrow(new Error('A user with this email already exists.')); + }); + + it('throws error when auth0 request fails', async () => { + jest + .spyOn(auth0Service, 'searchUsersByEmail') + .mockResolvedValueOnce([] as unknown as Auth0User); + jest + .spyOn(axios, 'post') + .mockRejectedValueOnce({ response: { data: {} } }); + + await expect( + auth0Service.createUser(userCreds.email, userCreds.password) + ).rejects.toThrow(); + }); + }); + + describe('updateUserMetadata', () => { + beforeEach(() => { + auth0Service = new Auth0Service(logger, axios, env); + jest + .spyOn(auth0Service, 'getAuth0AccessToken') + .mockResolvedValue('token'); + }); + + it('should updateUserMetadata updates metadata', async () => { + const newMetadata = { data: 'new' }; + jest + .spyOn(axios, 'patch') + .mockResolvedValueOnce({ ...auth0User, user_metadata: newMetadata }); + + const user = await auth0Service.updateUserMetadata('1', newMetadata); + + expect(user).toEqual({ ...auth0User, user_metadata: newMetadata }); + }); + }); + + describe('searchUsersByEmail', () => { + beforeEach(() => { + auth0Service = new Auth0Service(logger, axios, env); + jest + .spyOn(auth0Service, 'getAuth0AccessToken') + .mockResolvedValue('token'); + }); + + it('when the user is found', async () => { + jest.spyOn(axios, 'get').mockResolvedValueOnce({ data: auth0User }); + + const user = await auth0Service.searchUsersByEmail(auth0User.email); + + expect(user).toEqual(auth0User); + }); + + it('throws error when user is not found', async () => { + jest + .spyOn(axios, 'get') + .mockRejectedValueOnce({ response: { data: {} } }); + + await expect( + auth0Service.searchUsersByEmail(auth0User.email) + ).rejects.toThrow(); + }); + }); + + describe('deleteUser', () => { + beforeEach(() => { + auth0Service = new Auth0Service(logger, axios, env); + jest + .spyOn(auth0Service, 'getAuth0AccessToken') + .mockResolvedValue('token'); + }); + + it('when user is deleted', async () => { + jest.spyOn(axios, 'delete').mockResolvedValueOnce({}); + + const response = await auth0Service.deleteUser(auth0User.user_id); + + expect(response).toEqual({}); + }); + + it('throws error when auth0 request fails', async () => { + jest + .spyOn(axios, 'delete') + .mockRejectedValueOnce({ response: { data: {} } }); + + await expect( + auth0Service.deleteUser(auth0User.user_id) + ).rejects.toThrow(); + }); + }); + + describe('getAuth0AccessToken', () => { + beforeEach(() => { + auth0Service = new Auth0Service(logger, axios, env); + }); + + it('when accessToken is set', async () => { + const tokenResponse = { data: { access_token: 'token' } }; + jest.spyOn(axios, 'post').mockResolvedValueOnce(tokenResponse); + + auth0Service.getAuth0AccessToken(); + + // expect(onModuleInit).toHaveBeenCalled(); + }); + + it('throws error accessToken is missing', async () => { + const tokenResponse = { data: {} }; + jest.spyOn(axios, 'post').mockResolvedValueOnce(tokenResponse); + + await expect(auth0Service.getAuth0AccessToken()).rejects.toThrow( + new Error('Access token is missing!') + ); + expect(logger.error).toHaveBeenCalledWith( + 'Access token is missing in the response data' + ); + }); + + it('throws error when axios response is falsy(undefined)', async () => { + jest.spyOn(axios, 'post').mockResolvedValueOnce(undefined); + + await expect(auth0Service.getAuth0AccessToken()).rejects.toThrow( + new Error('Access token is missing!') + ); + }); + + it('throws error when auth0 token request fails', async () => { + jest + .spyOn(axios, 'post') + .mockRejectedValueOnce({ response: { data: {} } }); + + await expect(auth0Service.getAuth0AccessToken()).rejects.toThrow( + new Error('Something went wrong!') + ); + }); + }); +}); diff --git a/express-pg-auth0/src/api/auth/services/auth0.service.ts b/express-pg-auth0/src/api/auth/services/auth0.service.ts index 2efb658d..796249f6 100644 --- a/express-pg-auth0/src/api/auth/services/auth0.service.ts +++ b/express-pg-auth0/src/api/auth/services/auth0.service.ts @@ -13,18 +13,10 @@ export class Auth0Service { constructor( private logger: Logger, private axios: AxiosStatic, - private env: Environment, - ) { - this.getAuth0AccessToken() - .then((token) => { - this.accessToken = token; - }) - .catch((err) => { - throw err; - }); - } + private env: Environment + ) {} - private async getAuth0AccessToken() { + public async getAuth0AccessToken() { const response = await this.axios .post<{ access_token: string }>( `${this.baseURL}oauth/token`, @@ -53,11 +45,13 @@ export class Auth0Service { return response.data.access_token; } - private buildHeaders() { + private async buildHeaders() { + const accessToken = this.accessToken || (await this.getAuth0AccessToken()); + return { 'Content-Type': 'application/json', Accept: 'application/json', - Authorization: `Bearer ${this.accessToken}`, + Authorization: `Bearer ${accessToken}`, }; } @@ -69,6 +63,7 @@ export class Auth0Service { ); } + const headers = await this.buildHeaders(); return this.axios .post( `${this.baseURL}api/v2/users`, @@ -79,7 +74,7 @@ export class Auth0Service { password, verify_email: true, }, - { headers: this.buildHeaders() } + { headers } ) .then(({ data }) => data) .catch((error) => { @@ -88,24 +83,26 @@ export class Auth0Service { }); } - public updateUserMetadata( + public async updateUserMetadata( userId: string, metadata: Auth0User['user_metadata'] ) { + const headers = await this.buildHeaders(); return this.axios.patch( `${this.baseURL}api/v2/users/${userId}`, { user_metadata: metadata, }, - { headers: this.buildHeaders() } + { headers } ); } - public searchUsersByEmail(email: string) { + public async searchUsersByEmail(email: string) { + const headers = await this.buildHeaders(); return this.axios .get(`${this.baseURL}api/v2/users-by-email`, { params: { email }, - headers: this.buildHeaders(), + headers, }) .then(({ data }) => data) .catch((error) => { @@ -114,10 +111,11 @@ export class Auth0Service { }); } - public deleteUser(userId: string) { + public async deleteUser(userId: string) { + const headers = await this.buildHeaders(); return this.axios .delete(`${this.baseURL}api/v2/users/${userId}`, { - headers: this.buildHeaders(), + headers, }) .catch((error) => { this.logger.error(error.response.data); diff --git a/express-pg-auth0/src/api/todos/repositories/todos.repository.test.ts b/express-pg-auth0/src/api/todos/repositories/todos.repository.test.ts index 05e49d4d..9e4a7aad 100644 --- a/express-pg-auth0/src/api/todos/repositories/todos.repository.test.ts +++ b/express-pg-auth0/src/api/todos/repositories/todos.repository.test.ts @@ -12,6 +12,10 @@ describe('TodosRepository', () => { const todos = new TodosRepository(knex); const todosQb = knex('todos'); + afterEach(() => { + jest.clearAllMocks(); + }); + describe('insertOne', () => { it('should return the newly created record', async () => { const todo = { @@ -22,13 +26,7 @@ describe('TodosRepository', () => { }; jest.spyOn(todosQb, 'insert'); - jest.spyOn(todosQb, 'returning'); - jest.spyOn(todosQb, 'then'); - jest.spyOn(todosQb, 'catch').mockImplementationOnce(async () => ({ - ...todo, - createdAt: new Date().toISOString(), - updatedAt: new Date().toISOString(), - })); + jest.spyOn(todosQb, 'returning').mockReturnValue(Promise.resolve([todo]) as any); const result = await todos.insertOne(todo); @@ -37,8 +35,6 @@ describe('TodosRepository', () => { ...todo, }); expect(todosQb.returning).toHaveBeenCalledWith('*'); - expect(todosQb.then).toHaveBeenCalled(); - expect(todosQb.catch).toHaveBeenCalled(); expect(result).toEqual(expect.objectContaining(todo)); }); @@ -110,11 +106,7 @@ describe('TodosRepository', () => { jest.spyOn(todosQb, 'where'); jest.spyOn(todosQb, 'update'); - jest.spyOn(todosQb, 'returning'); - jest.spyOn(todosQb, 'then'); - jest - .spyOn(todosQb, 'catch') - .mockImplementationOnce(() => Promise.resolve(updated) as never); + jest.spyOn(todosQb, 'returning').mockReturnValue(Promise.resolve([updated]) as any); const result = await todos.updateById(todo.id, todo.userId, input); @@ -124,8 +116,6 @@ describe('TodosRepository', () => { }); expect(todosQb.update).toHaveBeenCalledWith(input); expect(todosQb.returning).toHaveBeenCalledWith('*'); - expect(todosQb.then).toHaveBeenCalled(); - expect(todosQb.catch).toHaveBeenCalled(); expect(result).toEqual(updated); }); diff --git a/express-pg-auth0/src/api/users/repositories/users.repository.test.ts b/express-pg-auth0/src/api/users/repositories/users.repository.test.ts index e60b0384..e8974f75 100644 --- a/express-pg-auth0/src/api/users/repositories/users.repository.test.ts +++ b/express-pg-auth0/src/api/users/repositories/users.repository.test.ts @@ -10,19 +10,18 @@ describe('UsersRepository', () => { const users = new UsersRepository(knex); const usersQb = knex('users'); + afterEach(() => { + jest.clearAllMocks(); + }); + describe('insertOne', () => { it('should return the newly created record', async () => { const user = { email: 'email@example.com', password: '123', userId: '1' }; jest.spyOn(usersQb, 'insert'); - jest.spyOn(usersQb, 'returning'); - jest.spyOn(usersQb, 'then'); - jest.spyOn(usersQb, 'catch').mockImplementationOnce(async () => ({ - id: 1, - ...user, - createdAt: new Date().toISOString(), - updatedAt: new Date().toISOString(), - })); + jest + .spyOn(usersQb, 'returning') + .mockReturnValue(Promise.resolve([user]) as any); const result = await users.insertOne(user); @@ -31,9 +30,6 @@ describe('UsersRepository', () => { ...user, }); expect(usersQb.returning).toHaveBeenCalledWith('*'); - expect(usersQb.then).toHaveBeenCalled(); - expect(usersQb.catch).toHaveBeenCalled(); - expect(result).toEqual(expect.objectContaining(user)); }); @@ -48,10 +44,12 @@ describe('UsersRepository', () => { .mockImplementationOnce(thenable as never); expect( - users.insertOne({ email: 'email@example.com', password: '123', userId: '1' }) - ).rejects.toThrow( - new DuplicateRecordError('User email already taken') - ); + users.insertOne({ + email: 'email@example.com', + password: '123', + userId: '1', + }) + ).rejects.toThrow(new DuplicateRecordError('User email already taken')); }); }); diff --git a/express-pg-auth0/src/app.test.ts b/express-pg-auth0/src/app.test.ts index 8b728946..9ea8cab4 100644 --- a/express-pg-auth0/src/app.test.ts +++ b/express-pg-auth0/src/app.test.ts @@ -7,7 +7,7 @@ describe('create', () => { it('should return an app instance and a destroy function', () => { const result = create({ PORT: 3000, - REQUEST_LOGGING: false, + REQUEST_LOGGING: true, ERROR_LOGGING: false, AUTH0_ISSUER_URL: 'AUTH0_ISSUER_URL', AUTH0_CLIENT_ID: 'AUTH0_CLIENT_ID', diff --git a/express-pg-auth0/src/utils/environment.test.ts b/express-pg-auth0/src/utils/environment.test.ts index fa56f67c..84aa707f 100644 --- a/express-pg-auth0/src/utils/environment.test.ts +++ b/express-pg-auth0/src/utils/environment.test.ts @@ -1,7 +1,48 @@ import { environmentSchema } from './environment'; -describe('envSchema', () => { - it('should be defined', () => { - expect(environmentSchema).toBeDefined(); +describe('Environment Schema', () => { + it('validates correct environment variables', () => { + const validEnv = { + NODE_ENV: 'development', + PORT: 3000, + REQUEST_LOGGING: 'true', + ERROR_LOGGING: 'false', + PGHOST: 'localhost', + PGPORT: 5432, + PGUSER: 'postgres', + PGPASSWORD: 'password', + PGDATABASE: 'testdb', + AUTH0_ISSUER_URL: 'https://example.com/', + AUTH0_CLIENT_ID: 'clientid', + AUTH0_AUDIENCE: 'audience', + AUTH0_CLIENT_SECRET: 'secret_secret_secret', + }; + + const data = environmentSchema.parse(validEnv); + + expect(data).toEqual( { + NODE_ENV: 'development', + PORT: 3000, + REQUEST_LOGGING: true, + ERROR_LOGGING: false, + PGHOST: 'localhost', + PGPORT: 5432, + PGUSER: 'postgres', + PGPASSWORD: 'password', + PGDATABASE: 'testdb', + AUTH0_ISSUER_URL: 'https://example.com/', + AUTH0_CLIENT_ID: 'clientid', + AUTH0_AUDIENCE: 'audience', + AUTH0_CLIENT_SECRET: 'secret_secret_secret' + }); + }); + + it('throws error for incorrect environment variables', () => { + const invalidEnv = { + NODE_ENV: 'invalid', + PORT: 'not a number', + }; + + expect(() => environmentSchema.parse(invalidEnv)).toThrow(); }); }); diff --git a/express-pg-auth0/src/utils/environment.ts b/express-pg-auth0/src/utils/environment.ts index c7a12b6d..ebf588b1 100644 --- a/express-pg-auth0/src/utils/environment.ts +++ b/express-pg-auth0/src/utils/environment.ts @@ -15,7 +15,6 @@ export const environmentSchema = z.object({ ERROR_LOGGING: z.enum(['true', 'false']).transform((value) => value === 'true'), // PostgreSQL - // TODO: this limits your options, should be revisited PGHOST: string, PGPORT: port, PGUSER: string, diff --git a/nest-mongo-auth0/src/api/auth/services/auth0.service.spec.ts b/nest-mongo-auth0/src/api/auth/services/auth0.service.spec.ts index 67988d34..d91eeb34 100644 --- a/nest-mongo-auth0/src/api/auth/services/auth0.service.spec.ts +++ b/nest-mongo-auth0/src/api/auth/services/auth0.service.spec.ts @@ -204,7 +204,7 @@ describe('Auth0Service', () => { it('throws error when axios response is falsy(undefined)', async () => { jest.spyOn(httpService.axiosRef, 'post').mockResolvedValueOnce(undefined); - await expect(auth0Service.onModuleInit()).rejects.toThrowError( + await expect(auth0Service.onModuleInit()).rejects.toThrow( new Error('Access token is missing!'), ); }); diff --git a/nest-mongo-jwt/src/api/auth/services/auth.service.spec.ts b/nest-mongo-jwt/src/api/auth/services/auth.service.spec.ts index a7a19226..27201f52 100644 --- a/nest-mongo-jwt/src/api/auth/services/auth.service.spec.ts +++ b/nest-mongo-jwt/src/api/auth/services/auth.service.spec.ts @@ -119,7 +119,7 @@ describe('AuthService', () => { email: registeredUser.email, password: registeredUser.password!, }), - ).rejects.toThrowError(new ConflictException('User email already taken')); + ).rejects.toThrow(new ConflictException('User email already taken')); }); }); @@ -127,7 +127,7 @@ describe('AuthService', () => { it('when the email is not registered should throw an error', async () => { jest.spyOn(usersRepository, 'findByEmail').mockResolvedValueOnce(null); - await expect(authService.login(unregisteredCreds)).rejects.toThrowError( + await expect(authService.login(unregisteredCreds)).rejects.toThrow( new UnprocessableEntityException('Invalid email or password'), ); }); @@ -139,7 +139,7 @@ describe('AuthService', () => { jest.spyOn(passwordService, 'compare').mockResolvedValueOnce(false); - await expect(authService.login(registeredCreds)).rejects.toThrowError( + await expect(authService.login(registeredCreds)).rejects.toThrow( new UnprocessableEntityException('Invalid email or password'), ); }); diff --git a/nest-pg-auth0/src/api/auth/services/auth.service.spec.ts b/nest-pg-auth0/src/api/auth/services/auth.service.spec.ts index a220ad49..36d2e467 100644 --- a/nest-pg-auth0/src/api/auth/services/auth.service.spec.ts +++ b/nest-pg-auth0/src/api/auth/services/auth.service.spec.ts @@ -95,7 +95,7 @@ describe('AuthService', () => { .spyOn(auth0Service, 'deleteUser') .mockResolvedValueOnce(auth0User as any); - await expect(authService.register(userCreds)).rejects.toThrowError( + await expect(authService.register(userCreds)).rejects.toThrow( new BadRequestException('Something went wrong!'), ); }); diff --git a/nest-pg-auth0/src/api/auth/services/auth0.service.spec.ts b/nest-pg-auth0/src/api/auth/services/auth0.service.spec.ts index 5d59b84d..faaca2a6 100644 --- a/nest-pg-auth0/src/api/auth/services/auth0.service.spec.ts +++ b/nest-pg-auth0/src/api/auth/services/auth0.service.spec.ts @@ -83,7 +83,7 @@ describe('Auth0Service', () => { await expect( auth0Service.createUser(userCreds.email, userCreds.password), - ).rejects.toThrowError( + ).rejects.toThrow( new BadRequestException('A user with this email already exists.'), ); }); @@ -98,7 +98,7 @@ describe('Auth0Service', () => { await expect( auth0Service.createUser(userCreds.email, userCreds.password), - ).rejects.toThrowError(new BadRequestException()); + ).rejects.toThrow(new BadRequestException()); }); }); @@ -131,11 +131,11 @@ describe('Auth0Service', () => { await expect( auth0Service.searchUsersByEmail(auth0User.email), - ).rejects.toThrowError(new BadRequestException()); + ).rejects.toThrow(new BadRequestException()); }); }); - describe('searchUsersByEmail', () => { + describe('deleteUser', () => { it('when user is deleted', async () => { jest.spyOn(httpService.axiosRef, 'delete').mockResolvedValueOnce({}); @@ -149,9 +149,9 @@ describe('Auth0Service', () => { .spyOn(httpService.axiosRef, 'delete') .mockRejectedValueOnce({ response: { data: {} } }); - await expect( - auth0Service.deleteUser(auth0User.user_id), - ).rejects.toThrowError(new BadRequestException()); + await expect(auth0Service.deleteUser(auth0User.user_id)).rejects.toThrow( + new BadRequestException(), + ); }); }); @@ -175,7 +175,7 @@ describe('Auth0Service', () => { .spyOn(httpService.axiosRef, 'post') .mockResolvedValueOnce(tokenResponse); - await expect(auth0Service.onModuleInit()).rejects.toThrowError( + await expect(auth0Service.onModuleInit()).rejects.toThrow( new Error('Access token is missing!'), ); }); @@ -183,7 +183,7 @@ describe('Auth0Service', () => { it('throws error when axios response is falsy(undefined)', async () => { jest.spyOn(httpService.axiosRef, 'post').mockResolvedValueOnce(undefined); - await expect(auth0Service.onModuleInit()).rejects.toThrowError( + await expect(auth0Service.onModuleInit()).rejects.toThrow( new Error('Access token is missing!'), ); }); @@ -193,7 +193,7 @@ describe('Auth0Service', () => { .spyOn(httpService.axiosRef, 'post') .mockRejectedValueOnce({ response: { data: {} } }); - await expect(auth0Service.onModuleInit()).rejects.toThrowError( + await expect(auth0Service.onModuleInit()).rejects.toThrow( new Error('Something went wrong!'), ); }); diff --git a/nest-pg-auth0/src/api/todos/todos.service.spec.ts b/nest-pg-auth0/src/api/todos/todos.service.spec.ts index 5f4e067e..1742c660 100644 --- a/nest-pg-auth0/src/api/todos/todos.service.spec.ts +++ b/nest-pg-auth0/src/api/todos/todos.service.spec.ts @@ -66,7 +66,7 @@ describe('TodosService', () => { .spyOn(repository, 'findOne') .mockImplementationOnce(async () => todo); - await expect(service.create(createTodoInput)).rejects.toThrowError( + await expect(service.create(createTodoInput)).rejects.toThrow( new UnprocessableEntityException(Errors.UnprocessableEntity), ); }); diff --git a/nest-pg-jwt/src/api/auth/services/auth.service.spec.ts b/nest-pg-jwt/src/api/auth/services/auth.service.spec.ts index 6aa0aa2f..1ceaa199 100644 --- a/nest-pg-jwt/src/api/auth/services/auth.service.spec.ts +++ b/nest-pg-jwt/src/api/auth/services/auth.service.spec.ts @@ -94,7 +94,7 @@ describe('AuthService', () => { email: registeredUser.email, password: registeredUser.password!, }), - ).rejects.toThrowError(new ConflictException('User email already taken')); + ).rejects.toThrow(new ConflictException('User email already taken')); }); }); @@ -104,7 +104,7 @@ describe('AuthService', () => { .spyOn(usersRepository, 'findByEmail') .mockResolvedValueOnce(undefined); - await expect(authService.login(unregisteredCreds)).rejects.toThrowError( + await expect(authService.login(unregisteredCreds)).rejects.toThrow( new UnprocessableEntityException('Invalid email or password'), ); }); @@ -116,7 +116,7 @@ describe('AuthService', () => { jest.spyOn(passwordService, 'compare').mockResolvedValueOnce(false); - await expect(authService.login(registeredCreds)).rejects.toThrowError( + await expect(authService.login(registeredCreds)).rejects.toThrow( new UnprocessableEntityException('Invalid email or password'), ); }); diff --git a/nest-pg-jwt/src/api/todos/todos.service.spec.ts b/nest-pg-jwt/src/api/todos/todos.service.spec.ts index aed86803..1742c660 100644 --- a/nest-pg-jwt/src/api/todos/todos.service.spec.ts +++ b/nest-pg-jwt/src/api/todos/todos.service.spec.ts @@ -66,7 +66,7 @@ describe('TodosService', () => { .spyOn(repository, 'findOne') .mockImplementationOnce(async () => todo); - await expect(service.create(createTodoInput)).rejects.toThrowError( + await expect(service.create(createTodoInput)).rejects.toThrow( new UnprocessableEntityException(Errors.UnprocessableEntity), ); }); @@ -155,7 +155,7 @@ describe('TodosService', () => { .spyOn(service, 'findOne') .mockImplementationOnce(async () => undefined); - await expect(service.remove({ id: '1', userId })).rejects.toThrowError( + await expect(service.remove({ id: '1', userId })).rejects.toThrow( new NotFoundException(Errors.NotFound), ); }); diff --git a/node-cli/assets/nest/example-app-pg/src/api/todos/todos.service.spec.ts b/node-cli/assets/nest/example-app-pg/src/api/todos/todos.service.spec.ts index 954077de..ea2167db 100644 --- a/node-cli/assets/nest/example-app-pg/src/api/todos/todos.service.spec.ts +++ b/node-cli/assets/nest/example-app-pg/src/api/todos/todos.service.spec.ts @@ -66,7 +66,7 @@ describe('TodosService', () => { .spyOn(repository, 'findOne') .mockImplementationOnce(async () => todo); - await expect(service.create(createTodoInput)).rejects.toThrowError( + await expect(service.create(createTodoInput)).rejects.toThrow( new UnprocessableEntityException(Errors.UnprocessableEntity), ); }); @@ -155,7 +155,7 @@ describe('TodosService', () => { .spyOn(service, 'findOne') .mockImplementationOnce(async () => undefined); - await expect(service.remove({ id: 1, userId })).rejects.toThrowError( + await expect(service.remove({ id: 1, userId })).rejects.toThrow( new NotFoundException(Errors.NotFound), ); }); diff --git a/node-cli/assets/nest/multiple-choice-features/authorization/mongodb/auth0/services/auth0.service.spec.ts b/node-cli/assets/nest/multiple-choice-features/authorization/mongodb/auth0/services/auth0.service.spec.ts index 67988d34..d91eeb34 100644 --- a/node-cli/assets/nest/multiple-choice-features/authorization/mongodb/auth0/services/auth0.service.spec.ts +++ b/node-cli/assets/nest/multiple-choice-features/authorization/mongodb/auth0/services/auth0.service.spec.ts @@ -204,7 +204,7 @@ describe('Auth0Service', () => { it('throws error when axios response is falsy(undefined)', async () => { jest.spyOn(httpService.axiosRef, 'post').mockResolvedValueOnce(undefined); - await expect(auth0Service.onModuleInit()).rejects.toThrowError( + await expect(auth0Service.onModuleInit()).rejects.toThrow( new Error('Access token is missing!'), ); }); diff --git a/node-cli/assets/nest/multiple-choice-features/authorization/mongodb/jwt/services/auth.service.spec.ts b/node-cli/assets/nest/multiple-choice-features/authorization/mongodb/jwt/services/auth.service.spec.ts index a7a19226..27201f52 100644 --- a/node-cli/assets/nest/multiple-choice-features/authorization/mongodb/jwt/services/auth.service.spec.ts +++ b/node-cli/assets/nest/multiple-choice-features/authorization/mongodb/jwt/services/auth.service.spec.ts @@ -119,7 +119,7 @@ describe('AuthService', () => { email: registeredUser.email, password: registeredUser.password!, }), - ).rejects.toThrowError(new ConflictException('User email already taken')); + ).rejects.toThrow(new ConflictException('User email already taken')); }); }); @@ -127,7 +127,7 @@ describe('AuthService', () => { it('when the email is not registered should throw an error', async () => { jest.spyOn(usersRepository, 'findByEmail').mockResolvedValueOnce(null); - await expect(authService.login(unregisteredCreds)).rejects.toThrowError( + await expect(authService.login(unregisteredCreds)).rejects.toThrow( new UnprocessableEntityException('Invalid email or password'), ); }); @@ -139,7 +139,7 @@ describe('AuthService', () => { jest.spyOn(passwordService, 'compare').mockResolvedValueOnce(false); - await expect(authService.login(registeredCreds)).rejects.toThrowError( + await expect(authService.login(registeredCreds)).rejects.toThrow( new UnprocessableEntityException('Invalid email or password'), ); }); diff --git a/node-cli/assets/nest/multiple-choice-features/authorization/pg/auth0/services/auth.service.spec.ts b/node-cli/assets/nest/multiple-choice-features/authorization/pg/auth0/services/auth.service.spec.ts index 15776ad0..1c4bc0d3 100644 --- a/node-cli/assets/nest/multiple-choice-features/authorization/pg/auth0/services/auth.service.spec.ts +++ b/node-cli/assets/nest/multiple-choice-features/authorization/pg/auth0/services/auth.service.spec.ts @@ -95,7 +95,7 @@ describe('AuthService', () => { .spyOn(auth0Service, 'deleteUser') .mockResolvedValueOnce(auth0User as any); - await expect(authService.register(userCreds)).rejects.toThrowError( + await expect(authService.register(userCreds)).rejects.toThrow( new BadRequestException('Something went wrong!'), ); }); diff --git a/node-cli/assets/nest/multiple-choice-features/authorization/pg/auth0/services/auth0.service.spec.ts b/node-cli/assets/nest/multiple-choice-features/authorization/pg/auth0/services/auth0.service.spec.ts index 5d59b84d..636f1e7d 100644 --- a/node-cli/assets/nest/multiple-choice-features/authorization/pg/auth0/services/auth0.service.spec.ts +++ b/node-cli/assets/nest/multiple-choice-features/authorization/pg/auth0/services/auth0.service.spec.ts @@ -83,7 +83,7 @@ describe('Auth0Service', () => { await expect( auth0Service.createUser(userCreds.email, userCreds.password), - ).rejects.toThrowError( + ).rejects.toThrow( new BadRequestException('A user with this email already exists.'), ); }); @@ -98,7 +98,7 @@ describe('Auth0Service', () => { await expect( auth0Service.createUser(userCreds.email, userCreds.password), - ).rejects.toThrowError(new BadRequestException()); + ).rejects.toThrow(new BadRequestException()); }); }); @@ -131,7 +131,7 @@ describe('Auth0Service', () => { await expect( auth0Service.searchUsersByEmail(auth0User.email), - ).rejects.toThrowError(new BadRequestException()); + ).rejects.toThrow(new BadRequestException()); }); }); @@ -151,7 +151,7 @@ describe('Auth0Service', () => { await expect( auth0Service.deleteUser(auth0User.user_id), - ).rejects.toThrowError(new BadRequestException()); + ).rejects.toThrow(new BadRequestException()); }); }); @@ -175,7 +175,7 @@ describe('Auth0Service', () => { .spyOn(httpService.axiosRef, 'post') .mockResolvedValueOnce(tokenResponse); - await expect(auth0Service.onModuleInit()).rejects.toThrowError( + await expect(auth0Service.onModuleInit()).rejects.toThrow( new Error('Access token is missing!'), ); }); @@ -183,7 +183,7 @@ describe('Auth0Service', () => { it('throws error when axios response is falsy(undefined)', async () => { jest.spyOn(httpService.axiosRef, 'post').mockResolvedValueOnce(undefined); - await expect(auth0Service.onModuleInit()).rejects.toThrowError( + await expect(auth0Service.onModuleInit()).rejects.toThrow( new Error('Access token is missing!'), ); }); @@ -193,7 +193,7 @@ describe('Auth0Service', () => { .spyOn(httpService.axiosRef, 'post') .mockRejectedValueOnce({ response: { data: {} } }); - await expect(auth0Service.onModuleInit()).rejects.toThrowError( + await expect(auth0Service.onModuleInit()).rejects.toThrow( new Error('Something went wrong!'), ); }); diff --git a/node-cli/assets/nest/multiple-choice-features/authorization/pg/jwt/services/auth.service.spec.ts b/node-cli/assets/nest/multiple-choice-features/authorization/pg/jwt/services/auth.service.spec.ts index 5799b204..c2122c09 100644 --- a/node-cli/assets/nest/multiple-choice-features/authorization/pg/jwt/services/auth.service.spec.ts +++ b/node-cli/assets/nest/multiple-choice-features/authorization/pg/jwt/services/auth.service.spec.ts @@ -94,7 +94,7 @@ describe('AuthService', () => { email: registeredUser.email, password: registeredUser.password!, }), - ).rejects.toThrowError(new ConflictException('User email already taken')); + ).rejects.toThrow(new ConflictException('User email already taken')); }); }); @@ -104,7 +104,7 @@ describe('AuthService', () => { .spyOn(usersRepository, 'findByEmail') .mockResolvedValueOnce(undefined); - await expect(authService.login(unregisteredCreds)).rejects.toThrowError( + await expect(authService.login(unregisteredCreds)).rejects.toThrow( new UnprocessableEntityException('Invalid email or password'), ); }); @@ -116,7 +116,7 @@ describe('AuthService', () => { jest.spyOn(passwordService, 'compare').mockResolvedValueOnce(false); - await expect(authService.login(registeredCreds)).rejects.toThrowError( + await expect(authService.login(registeredCreds)).rejects.toThrow( new UnprocessableEntityException('Invalid email or password'), ); });