From 5fe57368146222d65feba2e078a1e11f15152f02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Diego=20V=C3=A1zquez=20Campos?= Date: Tue, 13 Feb 2024 16:42:16 +0000 Subject: [PATCH] fix Unexpected empty object pattern. --- backend/src/modules/user/__tests__/usespe | 75 +++++++++++++++++++ frontend/.eslintrc | 10 +++ frontend/cypress/e2e/views/home.spec.cy.ts | 0 .../cypress/e2e/views/login-form.spec.cy.ts | 4 + frontend/src/store/auth/auth.module.ts | 31 ++++---- .../src/store/characters/characters.module.ts | 2 +- 6 files changed, 105 insertions(+), 17 deletions(-) create mode 100644 backend/src/modules/user/__tests__/usespe create mode 100644 frontend/.eslintrc create mode 100644 frontend/cypress/e2e/views/home.spec.cy.ts create mode 100644 frontend/cypress/e2e/views/login-form.spec.cy.ts diff --git a/backend/src/modules/user/__tests__/usespe b/backend/src/modules/user/__tests__/usespe new file mode 100644 index 0000000..574b932 --- /dev/null +++ b/backend/src/modules/user/__tests__/usespe @@ -0,0 +1,75 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { UserController } from '../user.controller'; +import { UserService } from '../user.service'; +import { getModelToken } from '@nestjs/mongoose'; +import { User, UserDocument } from '../user.schema'; +import { UserDto } from '../user.dto'; +import { UserModule } from '../user.module'; +import { omit } from 'lodash'; + +// Describe la suite de pruebas para el controlador de usuario. +describe('UserController', () => { + let userController: UserController; + let userService: UserService; + + const mockUser: UserDocument = { username: 'newuser', email: 'newuser@example.com', passwd: '1234', nickname: 'nickname' } as UserDocument; + let mockUsers = [ + { username: 'user1', email: 'user1@example.com' }, + { username: 'user2', email: 'user2@example.com' }, + ]; + + // Configura el controlador y sus dependencias antes de cada prueba. + beforeAll(async () => { + const module: TestingModule = await Test.createTestingModule({ + providers: [ + UserController, + UserService, + { + // Simula el modelo de mongoose para User durante las pruebas. + provide: getModelToken(User.name), + useValue: { + find: jest.fn(), // función simulada que imita "find" de mongoose + findOne: jest.fn(), // función simulada que imita "findOne" de mongoose + save: jest.fn(), // función simulada que imita "save" de mongoose, + exec: jest.fn(), // función simulada que imita "save" de mongoose + }, + }, + ], + }).compile(); // Compila el módulo de prueba y devuelve la instancia de TestingModule. + + userController = module.get(UserController); + userService = module.get(UserService); + + }); + + // Prueba básica para verificar si el controlador está definido. + it('should be defined', () => { + expect(userController).toBeDefined(); + }); + + // Prueba para verificar el si el tipo de los usuarios listados es correcto + describe('getUsers', () => { + it('should return an Array of type User', async () => { + jest.spyOn(userService, 'readUsers').mockImplementation(() => Promise.resolve(mockUsers as unknown as User[])); + const result = await userController.getUsers(); + expect(result).toEqual(mockUsers); + }) + }) + + describe('createUser', () => { + it('should create a new user', async () => { + jest.spyOn(userService, 'createUser').mockResolvedValueOnce(mockUser); + const result = await userController.createUser(mockUser as UserDto); + expect(result).toEqual(mockUser); + }); + }); + + describe('getUserByUsername', () => { + it('should return a user by username', async () => { + jest.spyOn(userService, 'readUserByUsername').mockResolvedValueOnce(mockUser); + const result = await userController.getUserByUsername('newuser'); + const keysToDelete = ['passwd']; + expect(result).toEqual(omit(mockUser, keysToDelete)); + }); + }); +}); \ No newline at end of file diff --git a/frontend/.eslintrc b/frontend/.eslintrc new file mode 100644 index 0000000..fb163ec --- /dev/null +++ b/frontend/.eslintrc @@ -0,0 +1,10 @@ +{ + "overrides": [ + { + "files": ["*.spec.cy.ts"], + "rules": { + "indent": "off" + } + } + ] + } \ No newline at end of file diff --git a/frontend/cypress/e2e/views/home.spec.cy.ts b/frontend/cypress/e2e/views/home.spec.cy.ts new file mode 100644 index 0000000..e69de29 diff --git a/frontend/cypress/e2e/views/login-form.spec.cy.ts b/frontend/cypress/e2e/views/login-form.spec.cy.ts new file mode 100644 index 0000000..e5ff8d9 --- /dev/null +++ b/frontend/cypress/e2e/views/login-form.spec.cy.ts @@ -0,0 +1,4 @@ +const testUser = { + email: 'testuser@example.com', + password: 'testpassword', +}; \ No newline at end of file diff --git a/frontend/src/store/auth/auth.module.ts b/frontend/src/store/auth/auth.module.ts index ddbdc2b..e3289ef 100644 --- a/frontend/src/store/auth/auth.module.ts +++ b/frontend/src/store/auth/auth.module.ts @@ -10,7 +10,7 @@ interface TrackingInformation { id: string; alias: string; type: string; - } +} const fieldMapping: { [key: string]: string } = { '/auth/login/email': 'email', @@ -57,9 +57,6 @@ export default { */ dismissToken: () => { - store.state["USERS"].user = undefined; - store.state["CHARACTERS"].characters = {}; - store.state["CHARACTERS"].currentCharacter = null; localStorage.removeItem("TokenSession"); location.reload(); } @@ -83,12 +80,9 @@ export default { async CHECK_TOKEN_EXPIRATION({ commit }: Triggers): Promise { try { const token = localStorage.TokenSession; - - if(token) { - const response = await axios.get(`${uri}/auth/expiration`, { headers: { authorization: `${token}` } }); - if (response.data.expired) commit('dismissToken'); // if expired dismiss token - } - + const response = await axios.get(`${uri}/auth/expiration`, { headers: { Authorization: `Bearer $` } }); + if (response.data.expired) commit('dismissToken'); // if expired dismiss token + if (!token) return; } catch (err) { throw new Error("Hubo un error verificando la sesión") } @@ -190,7 +184,7 @@ export default { * #param username - Carga útil para la verificación * #returns {Promise} - Devuelve true si el usuario existe, false en caso contrario. */ - async CHECK_USERNAME_EXISTENCE({ }: Triggers, username: string): Promise { + async CHECK_USERNAME_EXISTENCE(_: Triggers, username: string): Promise { try { const response = await axios.get(`${uri}/users/checkuser:${username}`); return response.data; @@ -205,7 +199,7 @@ export default { * #param email - Carga útil para la verificación * #returns {Promise} - Devuelve true si el correo electrónico existe, false en caso contrario. */ - async CHECK_EMAIL_EXISTENCE({ }: Triggers, email: any): Promise { + async CHECK_EMAIL_EXISTENCE(_: Triggers, email: any): Promise { try { const response = await axios.get(`${uri}/users/checkmail:${email}`); return response.data; @@ -214,12 +208,17 @@ export default { } }, + /** + * Acció para obtener la información de usuario dado un token + * #returns + */ - async GET_USER_INFO({ }: Triggers): Promise { + async GET_USER_INFO(_: Triggers): Promise { try { const token = localStorage.getItem("TokenSession"); + console.log(token) if (token) { - const response = await axios.get(`${uri}/auth/user-info`, { headers: { authorization: `${token}` } }); + const response = await axios.get(`${uri}/auth/user-info`, { headers: { Authorization: `Bearer ${token}` } }); return response.data; } else return {} @@ -234,7 +233,7 @@ export default { * #param data - data tracking. */ - async UPDATE_SOCKET_ASSOCIATION({}: Triggers, data:TrackingInformation): Promise { + async UPDATE_SOCKET_ASSOCIATION(_: Triggers, data: TrackingInformation): Promise { try { await axios.post(`${uri}/auth/updateSocketAssociation`, data); // Si necesitas realizar alguna acción adicional después de la actualización, puedes hacerlo aquí. @@ -242,6 +241,6 @@ export default { throw new Error('Error al actualizar la asociación del socket en el servidor'); } }, - + } } \ No newline at end of file diff --git a/frontend/src/store/characters/characters.module.ts b/frontend/src/store/characters/characters.module.ts index 79f61e0..7578a20 100644 --- a/frontend/src/store/characters/characters.module.ts +++ b/frontend/src/store/characters/characters.module.ts @@ -105,7 +105,7 @@ export default { * #throws {Error} Lanza un error si el nickname ya está en uso. * #returns {Promise} Devuelve true si el nickname no está en uso, de lo contrario, lanza un error. */ - async CHECK_NICKNAME_EXISTENCE({ }: Triggers, pjname: string): Promise { + async CHECK_NICKNAME_EXISTENCE(_: Triggers, pjname: string): Promise { try { // Realiza una llamada al backend para verificar la existencia del nickname const response = await axios.get(`${uri}/characters/check:${pjname}`);