Skip to content

Commit

Permalink
Merge pull request #27 from Arquisoft/zohaib
Browse files Browse the repository at this point in the history
Mejora de coverage y otros ajustes menores
  • Loading branch information
Verzidee authored Mar 31, 2024
2 parents 7f7429b + c88e45e commit 6ca0446
Show file tree
Hide file tree
Showing 14 changed files with 249 additions and 28 deletions.
4 changes: 2 additions & 2 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ services:
networks:
- mynetwork
environment:
MONGODB_URI: mongodb://mongodb:27017/userdb
MONGODB_URI: mongodb://mongodb:27017/questiondb

historyservice:
container_name: historyservice-${teamname:-wiq_es04d}
Expand All @@ -65,7 +65,7 @@ services:
networks:
- mynetwork
environment:
MONGODB_URI: mongodb://mongodb:27017/userdb
MONGODB_URI: mongodb://mongodb:27017/historydb

gatewayservice:
container_name: gatewayservice-${teamname:-defaultASW}
Expand Down
2 changes: 1 addition & 1 deletion questionservice/question-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const port = 8003;
// Importamos la función desde questionTemplates.js
const templates = require('./templates.json')
// Connect to MongoDB
const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/userdb';
const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/questiondb';
mongoose.connect(mongoUri);

const WikiQuery = require('./wikiUtils/wikiQuery');
Expand Down
2 changes: 1 addition & 1 deletion users/userservice/user-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const port = 8001;
app.use(bodyParser.json());

// Connect to MongoDB
const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/userdb';
const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/historydb';
mongoose.connect(mongoUri);


Expand Down
1 change: 0 additions & 1 deletion webapp/src/components/Button.css
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,4 @@
transition: all 0.3s ease-out;
background: #fff;
color: #242424;
transition: 250ms;
}
36 changes: 36 additions & 0 deletions webapp/src/components/CardItem.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import { BrowserRouter } from 'react-router-dom';
import CardItem from './CardItem';

describe('Componente CardItem', () => {
const mockProps = {
path: '/test-path',
label: 'Test Label',
src: 'test-img.jpg',
text: 'Test Text'
};

test('Renderiza correctamente con los props dados', () => {
render(
<BrowserRouter>
<CardItem {...mockProps} />
</BrowserRouter>
);

// Verifica que el componente Link lleve a la ruta correcta
expect(screen.getByRole('link')).toHaveAttribute('href', mockProps.path);

// Verifica que la imagen tenga el src correcto y alt text vacío
expect(screen.getByRole('img')).toHaveAttribute('src', mockProps.src);
expect(screen.getByRole('img')).toHaveAttribute('alt', '');

// Verifica que el texto sea correcto
expect(screen.getByText(mockProps.text)).toBeInTheDocument();

// Encuentra el elemento por su atributo data-category usando mockProps.label
// y verifica que el contenido sea correcto
const figure = document.querySelector(`[data-category='${mockProps.label}']`);
expect(figure).toBeInTheDocument();
});
});
23 changes: 23 additions & 0 deletions webapp/src/components/Layout.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import Layout from './Layout';

// Mock del componente Navbar para controlar su salida en el test
jest.mock('./Navbar', () => () => <div data-testid="navbar">Navbar</div>);

describe('Componente Layout', () => {
test('Renderiza el Navbar y el contenido de children correctamente', () => {
const childText = 'Contenido de prueba';
render(
<Layout>
<div>{childText}</div>
</Layout>
);

// Verifica que el Navbar se renderiza correctamente
expect(screen.getByTestId('navbar')).toBeInTheDocument();

// Verifica que el contenido de children se renderiza correctamente
expect(screen.getByText(childText)).toBeInTheDocument();
});
});
38 changes: 38 additions & 0 deletions webapp/src/components/Logout.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import React from 'react';
import { render } from '@testing-library/react';
import { BrowserRouter } from 'react-router-dom';
import { AuthContext } from '../AuthContext';
import Logout from './Logout';


// Mocks para las funciones que serán utilizadas por el componente
const mockHandleLogout = jest.fn();
const mockNavigate = jest.fn();

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

// Prueba para el componente Logout
describe('Logout Component', () => {
beforeEach(() => {
// Limpiar mocks antes de cada prueba
mockHandleLogout.mockClear();
mockNavigate.mockClear();
});

it('Llama a handleLogout y navega a la página de inicio en Mount', () => {
render(
<BrowserRouter>
<AuthContext.Provider value={{ handleLogout: mockHandleLogout }}>
<Logout />
</AuthContext.Provider>
</BrowserRouter>
);

// Verificar si handleLogout y navigate fueron llamados correctamente
expect(mockHandleLogout).toHaveBeenCalledTimes(1);
expect(mockNavigate).toHaveBeenCalledWith('/');
});
});
10 changes: 9 additions & 1 deletion webapp/src/components/Navbar.css
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,14 @@
background: #242222;
transition: all 0.5s ease;
}

.menu-icon button {
background: none;
border: none;
cursor: pointer;
color: #fff;
font-size: 1.8rem; /* Adjusted to ensure the icon inside the button matches your design */
padding: 0; /* Removes default button padding */
}
.nav-menu.active {
left: 0;
opacity: 1;
Expand All @@ -101,6 +108,7 @@
transition: all 0.3s ease-out;
}


.nav-links:hover {
background-color: #fff;
color: #242424;
Expand Down
9 changes: 6 additions & 3 deletions webapp/src/components/Navbar.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,14 @@ function Navbar() {
<div className='navbar-container'>
<Link to='/' className='navbar-logo' onClick={closeMenu}>WIQ<i className='fab fa-typo3' /></Link>
<div className='menu-icon' onClick={toggleClick}>
<i className={isClicked ? 'fas fa-times' : 'fas fa-bars'} />
<button aria-label="Menu toggle">
<i className={isClicked ? 'fas fa-times' : 'fas fa-bars'}/>
</button>
</div>
<NavLinks isLoggedIn={isLoggedIn} />

<NavLinks isLoggedIn={isLoggedIn}/>
{isLoggedIn ? (
showButton && <Button buttonStyle='btn--outline' to='/logout'>Salir</Button>
showButton && <Button buttonStyle='btn--outline' to='/logout'>Salir</Button>
) : (
<>
{showButton && <Button buttonStyle='btn--outline' to='/sign-up'>Registrarse</Button>}
Expand Down
66 changes: 66 additions & 0 deletions webapp/src/components/Navbar.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import { BrowserRouter as Router } from 'react-router-dom';
import Navbar from './Navbar';
import { AuthContext } from '../AuthContext';

// Función mock para simular el contexto de autenticación
const mockContext = (isLoggedIn) => ({
isLoggedIn
});

// Función de utilidad para renderizar el Navbar bajo diferentes condiciones
const renderNavbar = (contextValue, width = 1024) => {
window.innerWidth = width; // Simula el ancho de la ventana para pruebas de responsividad
return render(
<AuthContext.Provider value={mockContext(contextValue)}>
<Router>
<Navbar />
</Router>
</AuthContext.Provider>
);
};

describe('Componente Navbar', () => {
test('Se muestra correctamente cuando el usuario está logueado', () => {
renderNavbar(true);

expect(screen.getByRole('link', { name: 'Inicio' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Salir' })).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'Historial' })).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'Jugar' })).toBeInTheDocument();
});

test('Reacciona correctamente al redimensionar la ventana cuando el usuario está logueado', () => {
renderNavbar(true, 500);

fireEvent.click(screen.getByRole('button', { name: /Menu toggle/i }));
expect(screen.getByRole('link', { name: 'Salir' })).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'Historial' })).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'Jugar' })).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'Inicio' })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Salir' })).not.toBeInTheDocument();
});

test('Se muestra correctamente cuando el usuario no está logueado', () => {
renderNavbar(false);
expect(screen.getByRole('link', { name: 'Inicio' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Registrarse' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Entrar' })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Salir' })).not.toBeInTheDocument();
expect(screen.queryByRole('link', { name: 'Historial' })).not.toBeInTheDocument();
expect(screen.queryByRole('link', { name: 'Jugar' })).not.toBeInTheDocument();
});
test('Reacciona correctamente al redimensionar la ventana cuando el usuario no está logueado', () => {
renderNavbar(false, 500);

fireEvent.click(screen.getByRole('button', { name: /Menu toggle/i }));
expect(screen.getByRole('link', { name: 'Inicio' })).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'Registrarse' })).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'Entrar' })).toBeInTheDocument();
expect(screen.queryByRole('link', { name: 'Historial' })).not.toBeInTheDocument();
expect(screen.queryByRole('link', { name: 'Jugar' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Registrarse' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Entrar' })).not.toBeInTheDocument();
});
});
36 changes: 20 additions & 16 deletions webapp/src/components/pages/Error404Page.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,37 @@
import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button } from '../Button';
import './Error404Page.css'; // Asegúrate de tener este archivo en el mismo directorio
import './Error404Page.css';

function Error404Page() {
const navigate = useNavigate();
const [countdown, setCountdown] = useState(15);
function Error404Page({ initialCountdown = 15 }) {
const navigate = useNavigate(); // Hook para navegar programáticamente.
const [countdown, setCountdown] = useState(initialCountdown); // Estado para la cuenta regresiva

// Efecto que maneja la cuenta regresiva y redirige cuando llega a 0.
useEffect(() => {
if (countdown === 0) {
navigate('/');
navigate('/'); // Redirige a la página de inicio.
return;
}
// Establece un temporizador que decrementa 'countdown' cada segundo.
const timerId = setTimeout(() => setCountdown(countdown - 1), 1000);
// Limpieza: cancela el temporizador para evitar efectos secundarios.
return () => clearTimeout(timerId);
}, [countdown, navigate]);
}, [countdown, navigate]); // Dependencias del efecto.

// Renderizado de la página 404 con video de fondo y mensaje de cuenta regresiva.
return (
<div className="error-page-container">
<video autoPlay loop muted className="background-video">
<source src="videos/Error404.mp4" type="video/mp4" />
</video>
<div className="content">
<h1>404 - ¡Ups! Te quedaste sin oxígeno</h1>
<p>La página que estas buscando está fuera de nuestro alcance. Vamos a por ti.</p>
<div className="countdown">Vuelta al inicio en {countdown} segundos...</div>
<Button buttonStyle='btn--outline' to='/' sx={{ mt: 3, mb: 2 }}>Volver al Inicio</Button>
<div className="error-page-container">
<video autoPlay loop muted className="background-video">
<source src="videos/Error404.mp4" type="video/mp4" />
</video>
<div className="content">
<h1>404 - ¡Ups! Te quedaste sin oxígeno</h1>
<p>La página que estas buscando está fuera de nuestro alcance. Vamos a por ti.</p>
<div className="countdown">Vuelta al inicio en {countdown} segundos...</div>
<Button buttonStyle='btn--outline' to='/' sx={{ mt: 3, mb: 2 }}>Volver al Inicio</Button>
</div>
</div>
</div>
);
}

Expand Down
45 changes: 45 additions & 0 deletions webapp/src/components/pages/Error404Page.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import { BrowserRouter } from 'react-router-dom';
import Error404Page from './Error404Page';

const mockNavigate = jest.fn();
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useNavigate: () => mockNavigate,
}));
describe('Error404Page Tests', () => {
beforeEach(() => {
// Limpiar mocks antes de cada prueba
mockNavigate.mockClear();
});

test('renders 404 message', () => {
render(
<BrowserRouter>
<Error404Page />
</BrowserRouter>
);

// Verifica que el mensaje de 404 esté presente
expect(screen.getByText(/404 - ¡Ups! Te quedaste sin oxígeno/i)).toBeInTheDocument();
expect(screen.getByText(/La página que estas buscando está fuera de nuestro alcance/i)).toBeInTheDocument();
});
test('Go home after 15 seconds', () => {
render(
<BrowserRouter>
<Error404Page initialCountdown={0} />
</BrowserRouter>
);

expect(mockNavigate).toHaveBeenCalledWith('/');
});



});

async function wait(milliseconds) {
jest.advanceTimersByTime(milliseconds);
}
4 changes: 2 additions & 2 deletions webapp/src/components/pages/Home.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ describe('Home Component Tests', () => {
test('renders Home component correctly', () => {
renderWithRouter(<Home />);
expect(screen.getByRole('heading', { name: /wiq/i })).toBeInTheDocument();
expect(screen.getByText(/¿A que estás esperando?\?/i)).toBeInTheDocument();
expect(screen.getByText(/JUGAR/i)).toBeInTheDocument();
expect(screen.getByText(/¿A que estás esperando?/i)).toBeInTheDocument();
expect(screen.getByText(/jugar/i)).toBeInTheDocument();
});

test('loads and plays the video automatically', () => {
Expand Down
1 change: 0 additions & 1 deletion webapp/src/components/pages/Jugar.css
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,6 @@ body, html {
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s;
display: block; /* Asegura que el botón sea un bloque */
width: 100%; /* Hace que el botón ocupe todo el ancho disponible */
box-sizing: border-box; /* Asegura que el padding no afecte el ancho final */
Expand Down

0 comments on commit 6ca0446

Please sign in to comment.