Skip to content

Commit

Permalink
Merge branch 'develop' into Pablo-Despliegue
Browse files Browse the repository at this point in the history
  • Loading branch information
uo289432 committed Apr 10, 2024
2 parents 97e8066 + 041e654 commit eb47e16
Show file tree
Hide file tree
Showing 11 changed files with 277 additions and 99 deletions.
1 change: 1 addition & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ on:
branches:
- master
- develop
- LaraFMz
pull_request:
types: [opened, synchronize, reopened]
jobs:
Expand Down
3 changes: 3 additions & 0 deletions sonar-project.properties
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,12 @@ sonar.host.url=https://sonarcloud.io
sonar.language=js
sonar.projectName=wiq_es05a

# Sonar exclusions
sonar.coverage.exclusions=**/*.test.js
sonar.coverage.exclusions=**/*.json, **/*.yaml
sonar.coverage.exclusions=**/Dockerfile, **/*.dockerfile
sonar.coverage.exclusions=webapp/src/components/tests/**
# Sonar sources
sonar.sources=webapp/src/components,userservice/authservice,userservice/userservice,gatewayservice,questionservice
sonar.sourceEncoding=UTF-8
sonar.exclusions=node_modules/**
Expand Down
95 changes: 0 additions & 95 deletions webapp/src/components/Pages/Juego.test.js

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React from 'react';
import { render, fireEvent, screen, waitFor } from '@testing-library/react';
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import AddUser from './AddUser';
import AddUser from '../AddUser';

const mockAxios = new MockAdapter(axios);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React from 'react';
import { render, waitFor } from '@testing-library/react';
import axiosMock from 'axios';
import Estadisticas from './Estadisticas';
import Estadisticas from '../Pages/Estadisticas';

// Mock de datos para simular la respuesta del servidor
const mockUserData = {
Expand Down
64 changes: 64 additions & 0 deletions webapp/src/components/tests/Home.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import Home from '../Pages/Home';
import { BrowserRouter as Router } from "react-router-dom";

const mockNavigate = jest.fn();

jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useNavigate: () => mockNavigate,
}));

describe('Home component', () => {
it('renders "INICIA SESIÓN" and "REGÍSTRATE" buttons when not logged in', () => {
const { getByText } = render(<Router><Home isLogged={false} /></Router>);

// Verifica que el título del juego esté presente
expect(getByText('WIQ 5A')).toBeInTheDocument();

// Verifica que los botones "INICIA SESIÓN" y "REGÍSTRATE" estén presentes
expect(getByText('INICIA SESIÓN')).toBeInTheDocument();
expect(getByText('REGÍSTRATE')).toBeInTheDocument();
});

it('renders "JUGAR" and "ESTADÍSTICAS" buttons when logged in', () => {
const { getByText } = render(<Router><Home isLogged={true} /></Router>);

// Verifica que el título del juego esté presente
expect(getByText('WIQ 5A')).toBeInTheDocument();

// Verifica que los botones "JUGAR" y "ESTADÍSTICAS" estén presentes
expect(getByText('JUGAR')).toBeInTheDocument();
expect(getByText('ESTADÍSTICAS')).toBeInTheDocument();
});

it('clicking "INICIA SESIÓN" button navigates to "/login"', () => {
const { getByText } = render(<Router><Home isLogged={false} /></Router>);
const button = getByText('INICIA SESIÓN');
fireEvent.click(button);
expect(mockNavigate).toHaveBeenCalledWith('/login');
});

it('clicking "REGÍSTRATE" button navigates to "/register"', () => {
const { getByText } = render(<Router><Home isLogged={false} /></Router>);
const button = getByText('REGÍSTRATE');
fireEvent.click(button);
expect(mockNavigate).toHaveBeenCalledWith('/register');
});

it('clicking "JUGAR" button navigates to "/game"', () => {
const { getByText } = render(<Router><Home isLogged={true} /></Router>);
const button = getByText('JUGAR');
fireEvent.click(button);
expect(mockNavigate).toHaveBeenCalledWith('/game');
});

it('clicking "ESTADÍSTICAS" button navigates to "/stats"', () => {
const { getByText } = render(<Router><Home isLogged={true} /></Router>);
const button = getByText('ESTADÍSTICAS');
fireEvent.click(button);
expect(mockNavigate).toHaveBeenCalledWith('/stats');
})

});
120 changes: 120 additions & 0 deletions webapp/src/components/tests/Juego.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import React from 'react';
import { render, fireEvent, waitFor } from '@testing-library/react';
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import Juego from '../Pages/Juego';
import '@testing-library/jest-dom/extend-expect';
import { act } from 'react-dom/test-utils';

jest.useFakeTimers();

describe('Juego component', () => {
let mock;
//Toda la informacion mockeada
//Para las preguntas
const mockData = {
question: '¿Cuál es la capital de Francia?',
answerGood: 'París',
answers: ['Londres', 'Madrid', 'Berlín', 'París']
};
//Para actualizar estadísticas
const responseData = { success: true };
const apiEndpoint = process.env.REACT_APP_API_ENDPOINT || 'http://localhost:8000';

beforeEach(() => {
mock = new MockAdapter(axios);
//Al hacer la llamada a la pregunta, devolvemos la informacion mockeada
mock.onGet('http://localhost:8000/pregunta').reply(200, mockData);
//Al hacer la llamada a la ruta de actualizar estadisticas, devolvemos el resultado mockeado
mock.onGet('http://localhost:8000/updateStats?username=test&numRespuestasCorrectas=0&numRespuestasIncorrectas=0').reply(200,responseData);
});

afterEach(() => {
mock.restore();
});

it('obtiene las preguntas y respuestas', async () => {
const { container, getByText } = render(<Juego isLogged={true} username="test" numPreguntas={1} />);

await waitFor(() => getByText('CARGANDO...'));

await waitFor(() => getByText(mockData.question));

expect(getByText('¿Cuál es la capital de Francia?')).toBeInTheDocument();
expect(getByText('París')).toBeInTheDocument();
expect(getByText('Londres')).toBeInTheDocument();
expect(getByText('Berlín')).toBeInTheDocument();
expect(getByText('Madrid')).toBeInTheDocument();
expect(getByText('1 / 1')).toBeInTheDocument();
});

it('responde la pregunta correctamente', async () => {
const { container, getByText } = render(<Juego isLogged={true} username="test" numPreguntas={1} />);

await waitFor(() => getByText(mockData.question));

fireEvent.click(getByText('París'));
expect(getByText('París')).toHaveStyle('background-color: #05B92B; border: 6px solid #05B92B');
//Todos los botones deben deshabilitarse
expect(getByText('París')).toBeDisabled();
expect(getByText('Londres')).toBeDisabled();
expect(getByText('Berlín')).toBeDisabled();
expect(getByText('Madrid')).toBeDisabled();
});

it('responde la pregunta incorrectamente y despinta al hacer click en Siguiente', async () => {
const { container, getByText } = render(<Juego isLogged={true} username="test" numPreguntas={2} />);

await waitFor(() => getByText(mockData.question));

fireEvent.click(getByText('Londres'));
expect(getByText('Londres')).toHaveStyle('background-color: #E14E4E; border: 6px solid #E14E4E');
//La correcta se pone en verde
expect(getByText('París')).toHaveStyle('background-color: #05B92B; border: 6px solid #05B92B');
//Todos los botones deben deshabilitarse
expect(getByText('París')).toBeDisabled();
expect(getByText('Londres')).toBeDisabled();
expect(getByText('Berlín')).toBeDisabled();
expect(getByText('Madrid')).toBeDisabled();

//Al hacer click en Siguiente, se habilitan los botones y se despintan
fireEvent.click(getByText('SIGUIENTE'));
await waitFor(() => getByText(mockData.question));
expect(getByText('París')).toBeEnabled();
expect(getByText('Londres')).toBeEnabled();
expect(getByText('Berlín')).toBeEnabled();
expect(getByText('Madrid')).toBeEnabled();
expect(getByText('París')).toHaveStyle('background-color: #FFFFFF');
expect(getByText('París')).toHaveStyle('background-color: #FFFFFF');
expect(getByText('París')).toHaveStyle('background-color: #FFFFFF');
expect(getByText('París')).toHaveStyle('background-color: #FFFFFF');

});

it('finalizar Juego', async () => {
const { container, getByText } = render(<Juego isLogged={true} username="test" numPreguntas={1} />);
await waitFor(() => getByText(mockData.question));
fireEvent.click(getByText('SIGUIENTE'));
fireEvent.click(getByText('FINALIZAR PARTIDA'));
expect(getByText('FINALIZAR PARTIDA')).toBeDisabled();
console.log(container.numRespuestasCorrectas)
//expect(axios.get).toHaveBeenCalledWith('http://localhost:8000/updateStats?username=test&numRespuestasCorrectas=0&numRespuestasIncorrectas=0');
});

it('el temporizador llega a 0 y se desvelan las respuestas ademas de bloquearse los botones', async () => {
const { container, getByText } = render(<Juego isLogged={true} username="test" numPreguntas={1} />);

await waitFor(() => getByText(mockData.question));
act(() => {
jest.advanceTimersByTime(30000); // Espera 30 segundos
});
expect(getByText('París')).toBeDisabled();
expect(getByText('Londres')).toBeDisabled();
expect(getByText('Berlín')).toBeDisabled();
expect(getByText('Madrid')).toBeDisabled();
});




});
57 changes: 57 additions & 0 deletions webapp/src/components/tests/Layout.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect'; // Extiende las expectativas de Jest
import Layout from '../Pages/Layout'; // Importa el componente a probar
import { BrowserRouter as Router } from "react-router-dom";

describe('Layout component', () => {
// Mock de setIsLogged
const setIsLogged = jest.fn();

// Mock de localStorage.setItem
const mockLocalStorageSetItem = jest.spyOn(window.localStorage.__proto__, 'setItem');

// Props para el estado de inicio de sesión
const initialLoggedInProps = {
isLogged: true,
setIsLogged: setIsLogged,
};

// Props para el estado sin inicio de sesión
const initialLoggedOutProps = {
isLogged: false,
setIsLogged: setIsLogged,
};

// Configuración inicial de la prueba
beforeEach(() => {
setIsLogged.mockClear(); // Limpiar los mocks antes de cada prueba
mockLocalStorageSetItem.mockClear();
});

it('renders navigation links correctly when logged out', () => {
// Renderiza el componente con las props sin inicio de sesión
const { getByText, queryByText } = render(<Router><Layout {...initialLoggedOutProps} /></Router>);

// Verifica que los enlaces de "Inicia Sesión" y "Regístrate" estén presentes
expect(getByText('Inicia Sesión')).toBeInTheDocument();
expect(getByText('Regístrate')).toBeInTheDocument();

// Verifica que el botón "Estadísticas" no esté presente
expect(queryByText('Estadísticas')).not.toBeInTheDocument();
});

it('clicking "Cerrar sesión" button logs out user', () => {
// Renderiza el componente con las props de inicio de sesión
const { getByText } = render(<Layout {...initialLoggedInProps} />);

// Simula hacer clic en el botón "Cerrar sesión"
fireEvent.click(getByText('Cerrar sesión'));

// Verifica que setIsLogged haya sido llamado con false
expect(setIsLogged).toHaveBeenCalledWith(false);

// Verifica que localStorage.setItem haya sido llamado con false
expect(mockLocalStorageSetItem).toHaveBeenCalledWith('isLogged', JSON.stringify(false));
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React from 'react';
import { render, fireEvent, screen, waitFor, act } from '@testing-library/react';
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import Login from './Login';
import Login from '../Login';
import userEvent from '@testing-library/user-event'

const mockAxios = new MockAdapter(axios);
Expand Down
Loading

0 comments on commit eb47e16

Please sign in to comment.