Skip to content

Commit

Permalink
fix Unexpected empty object pattern.
Browse files Browse the repository at this point in the history
  • Loading branch information
dkaerit committed Feb 13, 2024
1 parent 4ba4a45 commit 5fe5736
Show file tree
Hide file tree
Showing 6 changed files with 105 additions and 17 deletions.
75 changes: 75 additions & 0 deletions backend/src/modules/user/__tests__/usespe
Original file line number Diff line number Diff line change
@@ -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: '[email protected]', passwd: '1234', nickname: 'nickname' } as UserDocument;
let mockUsers = [
{ username: 'user1', email: '[email protected]' },
{ username: 'user2', email: '[email protected]' },
];

// 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>(UserController);
userService = module.get<UserService>(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));
});
});
});
10 changes: 10 additions & 0 deletions frontend/.eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"overrides": [
{
"files": ["*.spec.cy.ts"],
"rules": {
"indent": "off"
}
}
]
}
Empty file.
4 changes: 4 additions & 0 deletions frontend/cypress/e2e/views/login-form.spec.cy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
const testUser = {
email: '[email protected]',
password: 'testpassword',
};
31 changes: 15 additions & 16 deletions frontend/src/store/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ interface TrackingInformation {
id: string;
alias: string;
type: string;
}
}

const fieldMapping: { [key: string]: string } = {
'/auth/login/email': 'email',
Expand Down Expand Up @@ -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();
}
Expand All @@ -83,12 +80,9 @@ export default {
async CHECK_TOKEN_EXPIRATION({ commit }: Triggers): Promise<void> {
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")
}
Expand Down Expand Up @@ -190,7 +184,7 @@ export default {
* #param username - Carga útil para la verificación
* #returns {Promise<boolean>} - Devuelve true si el usuario existe, false en caso contrario.
*/
async CHECK_USERNAME_EXISTENCE({ }: Triggers, username: string): Promise<boolean> {
async CHECK_USERNAME_EXISTENCE(_: Triggers, username: string): Promise<boolean> {
try {
const response = await axios.get(`${uri}/users/checkuser:${username}`);
return response.data;
Expand All @@ -205,7 +199,7 @@ export default {
* #param email - Carga útil para la verificación
* #returns {Promise<boolean>} - Devuelve true si el correo electrónico existe, false en caso contrario.
*/
async CHECK_EMAIL_EXISTENCE({ }: Triggers, email: any): Promise<boolean> {
async CHECK_EMAIL_EXISTENCE(_: Triggers, email: any): Promise<boolean> {
try {
const response = await axios.get(`${uri}/users/checkmail:${email}`);
return response.data;
Expand All @@ -214,12 +208,17 @@ export default {
}
},

/**
* Acció para obtener la información de usuario dado un token
* #returns
*/

async GET_USER_INFO({ }: Triggers): Promise<UserData | {}> {
async GET_USER_INFO(_: Triggers): Promise<UserData | {}> {
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 {}

Expand All @@ -234,14 +233,14 @@ export default {
* #param data - data tracking.
*/

async UPDATE_SOCKET_ASSOCIATION({}: Triggers, data:TrackingInformation): Promise<void> {
async UPDATE_SOCKET_ASSOCIATION(_: Triggers, data: TrackingInformation): Promise<void> {
try {
await axios.post(`${uri}/auth/updateSocketAssociation`, data);
// Si necesitas realizar alguna acción adicional después de la actualización, puedes hacerlo aquí.
} catch (error) {
throw new Error('Error al actualizar la asociación del socket en el servidor');
}
},

}
}
2 changes: 1 addition & 1 deletion frontend/src/store/characters/characters.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ export default {
* #throws {Error} Lanza un error si el nickname ya está en uso.
* #returns {Promise<boolean>} Devuelve true si el nickname no está en uso, de lo contrario, lanza un error.
*/
async CHECK_NICKNAME_EXISTENCE({ }: Triggers, pjname: string): Promise<boolean> {
async CHECK_NICKNAME_EXISTENCE(_: Triggers, pjname: string): Promise<boolean> {
try {
// Realiza una llamada al backend para verificar la existencia del nickname
const response = await axios.get(`${uri}/characters/check:${pjname}`);
Expand Down

0 comments on commit 5fe5736

Please sign in to comment.