Skip to content

Commit

Permalink
Merge branch 'master' of https://github.com/Arquisoft/wiq_en3a
Browse files Browse the repository at this point in the history
  • Loading branch information
sergiollende committed Apr 28, 2024
2 parents ce62640 + f1beddc commit d1feb39
Show file tree
Hide file tree
Showing 6 changed files with 286 additions and 20 deletions.
28 changes: 26 additions & 2 deletions webapp/src/components/Game/Countdown.test.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import React from 'react';
import { render, fireEvent, screen } from '@testing-library/react';
import { render, fireEvent, screen, act } from '@testing-library/react';
import Countdown from './Countdown';

jest.useFakeTimers();

describe('Countdown component', () => {
const mockedProps = {
duration: 3,
Expand All @@ -12,5 +14,27 @@ describe('Countdown component', () => {

expect(screen.getByText('Next Question In: 3')).toBeInTheDocument();
});
});

test('Countdown renders 3 and then 0 after the countdown', async () => {
render(<Countdown {...mockedProps} />);

expect(screen.getByText('Next Question In: 3')).toBeInTheDocument();

// Avanzar el temporizador en 2 segundos
jest.advanceTimersByTime(2000);

// Comprobar que el texto sigue siendo 3 después de 2 segundos
expect(screen.getByText('Next Question In: 3')).toBeInTheDocument();

// Avanzar el temporizador en otros 1 segundo
act(() => {
jest.advanceTimersByTime(1000);
});

// Comprobar que el texto ahora es 0 después de 3 segundos en total
act(() => {
expect(screen.getByText('Next Question In: 0')).toBeInTheDocument();
});
});
});

62 changes: 61 additions & 1 deletion webapp/src/components/Game/Counter.test.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,19 @@
import React from 'react';
import { render, fireEvent, screen } from '@testing-library/react';
import { render, fireEvent, screen, act } from '@testing-library/react';
import Counter from './Counter';

const mockSetCount = jest.fn();

describe('Counter component', () => {
beforeEach(() => {
jest.useFakeTimers(); // Usar timers falsos
});

afterEach(() => {
jest.clearAllMocks();
jest.useRealTimers(); // Restaurar timers reales
});

const mockedProps = {
answered: false,
setAnswered: jest.fn(),
Expand All @@ -17,4 +28,53 @@ describe('Counter component', () => {
expect(screen.findByTestId('counter'));
});

test('calls setCount every 100ms', () => {
const props = {
answered: false,
setAnswered: jest.fn(),
duration: 1000, // Duración del contador (en milisegundos)
count: 5,
setCount: mockSetCount,
initialCount: 5,
};

render(<Counter {...props} />);

// Avanzar 100ms
act(() => {
jest.advanceTimersByTime(100);
});

expect(mockSetCount).toHaveBeenCalledTimes(1);

// Avanzar 100ms adicionales
act(() => {
jest.advanceTimersByTime(100);
});

expect(mockSetCount).toHaveBeenCalledTimes(2);

});

test('stops the timer when answered', () => {
const props = {
answered: true,
setAnswered: jest.fn(),
duration: 1000,
count: 5,
setCount: mockSetCount,
initialCount: 5,
};

render(<Counter {...props} />);

// Avanzar 1000ms
act(() => {
jest.advanceTimersByTime(1000);
});

// Asegurarse de que el contador no se haya decrementado
expect(mockSetCount).not.toHaveBeenCalled();
});

});
23 changes: 22 additions & 1 deletion webapp/src/components/Game/Trivia/TriviaQuestion.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const mockProps: props = {
category: 1,
setLifesNumber: jest.fn(),
lifes: 3,
};
};

describe('TriviaQuestion', () => {
it('renders correctly', () => {
Expand All @@ -38,4 +38,25 @@ describe('TriviaQuestion', () => {
fireEvent.click(getByText('Answer 2'));
await waitFor(() => expect(mockProps.setLifesNumber).toHaveBeenCalledWith(2));
});

it('calls setIsShowingQuestion(false) after 2 seconds when answered', async () => {
jest.useFakeTimers(); // Activar el uso de temporizadores falsos

const { getByText } = render(<TriviaQuestion {...mockProps} />);
fireEvent.click(getByText('Answer 1'));

// Avanzar en el tiempo en 2000ms
jest.advanceTimersByTime(2000);

await waitFor(() => {
expect(mockProps.setIsShowingQuestion).toHaveBeenCalledWith(false);
});

jest.useRealTimers(); // Restaurar temporizadores reales
});

it('returns "No question available" when question is null', () => {
const { getByText } = render(<TriviaQuestion {...mockProps} questionShowed={null} />);
expect(getByText('No question available')).toBeInTheDocument();
});
});
15 changes: 15 additions & 0 deletions webapp/src/components/auth/AddUser.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,21 @@ describe('AddUser', () => {
render(<AddUser onRegistrationCompleted={mockOnRegistrationCompleted} />);
});

test('displays error message when registration fails', async () => {
const errorMessage = 'Registration failed: Email already exists';
mockRegister.mockResolvedValueOnce({ error: true, message: errorMessage });

render(<AddUser onRegistrationCompleted={mockOnRegistrationCompleted} />);

const registerButton = screen.getByRole('button', { name: 'Create account' });
fireEvent.click(registerButton);

// Wait for the error message to be displayed
await screen.findByText(`Error: ${errorMessage}`);

expect(mockOnRegistrationCompleted).not.toHaveBeenCalled();
});

test('updates input fields correctly', () => {
render(<AddUser onRegistrationCompleted={mockOnRegistrationCompleted} />);
const usernameInput = screen.getByLabelText('Username') as HTMLInputElement;
Expand Down
20 changes: 20 additions & 0 deletions webapp/src/components/general/Home.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,26 @@ import { Home } from './Home';
import { BrowserRouter as Router } from 'react-router-dom'; // Importa BrowserRouter

describe('Home component', () => {

it('should update selectedOption state when radio button is clicked', () => {
render(
<Router>
<Home />
</Router>
);

const radioButton = screen.getByLabelText('Easy'); // Obtén el radio button por su etiqueta
fireEvent.click(radioButton); // Simula un clic en el radio button

expect(screen.getByLabelText('Easy')).toBeChecked(); // Verifica que el radio button esté marcado
expect(screen.queryByLabelText('Hard')).not.toBeChecked(); // Verifica que el otro radio button no esté marcado

fireEvent.click(screen.getByLabelText('Hard')); // Simula un clic en el otro radio button

expect(screen.getByLabelText('Hard')).toBeChecked(); // Verifica que el otro radio button esté marcado
expect(screen.queryByLabelText('Easy')).not.toBeChecked(); // Verifica que el primer radio button no esté marcado
});

it('should render the "Start Game!" button when not playing', () => {
render(
<Router>
Expand Down
158 changes: 142 additions & 16 deletions webapp/src/services/auth-service.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ describe('AuthService functions', () => {
jest.clearAllMocks();
});




it('register function', async () => {
// Configura el comportamiento simulado de axios.post
const responseData = { data: 'invented' };
Expand All @@ -37,29 +40,36 @@ describe('AuthService functions', () => {
expect(result.message).toBe(responseData.data);
});

it('register with invalid credentials', async () => {
it('register with invalid credentials', async () => {
// Configurar el comportamiento simulado de axios.post para que devuelva un error
const errorMessage = 'Request failed';
axios.post = jest.fn().mockResolvedValueOnce((new Error(errorMessage)));

const errorMessage = 'Error: Username already exists';
axios.post = jest.fn().mockRejectedValueOnce({ response: { data: { error: errorMessage } } });
// Llamar a la función que quieres probar
expect(await register('a', 'invalid', 'credentials')).toStrictEqual({'error': false, 'message': undefined}); //undefined bc it doesn't register
const result = await register('test@email.com', 'testuser', 'password123');

// Verificar que axios.post haya sido llamado con la URL y los datos correctos
expect(axios.post).toHaveBeenCalledWith('http://localhost:8000/adduser', { email: 'test@email.com', username: 'testuser', password: 'password123' });

// Verificar que la función devuelva un objeto con error: true y el mensaje de error correspondiente
expect(result).toEqual({ error: true, message: errorMessage });
});

it('login with correct credentials', async () => {
// Configura el comportamiento simulado de axios.post
const responseData = { data: 'Mocked data response' };
axios.post = jest.fn().mockResolvedValueOnce(responseData);

// Llama a la función que quieres probar
const result = await login('tomas', '0000');
it('login with correct credentials', async () => {
// Configura el comportamiento simulado de axios.post
const responseData = { data: 'Mocked data response' };
axios.post = jest.fn().mockResolvedValueOnce(responseData);

// Verifica que axios.post haya sido llamado con la URL y los datos correctos
expect(axios.post).toHaveBeenCalledWith('http://localhost:8000/login', { username: 'tomas', password: '0000' });
// Llama a la función que quieres probar
const result = await login('tomas', '0000');

// Verifica que la función devuelva los datos simulados
expect(result).toBe(true);
});
// Verifica que axios.post haya sido llamado con la URL y los datos correctos
expect(axios.post).toHaveBeenCalledWith('http://localhost:8000/login', { username: 'tomas', password: '0000' });

// Verifica que la función devuelva los datos simulados
expect(result).toBe(true);
});

it('login with invalid credentials', async () => {
// Configurar el comportamiento simulado de axios.post para que devuelva un error
Expand All @@ -70,4 +80,120 @@ describe('AuthService functions', () => {
expect(await login('invalid', 'credentials')).toBe(false);
});


it('get all users', async () => {
// Configura el comportamiento simulado de axios.get
const responseData = { data: ['user1', 'user2', 'user3'] };
axios.get = jest.fn().mockResolvedValueOnce(responseData);

// Llama a la función que quieres probar
const result = await getAllUsers();

// Verifica que axios.get haya sido llamado con la URL correcta
expect(axios.get).toHaveBeenCalledWith('http://localhost:8000/getAllUsers', {});

// Verifica que la función devuelva los datos simulados
expect(result).toEqual(responseData.data);
});

it('get all users with error', async () => {
// Mock axios.get para simular una respuesta de error
const errorMessage = 'Request failed';
axios.get = jest.fn().mockRejectedValueOnce(new Error(errorMessage));

// Llama a la función que quieres probar
try {
await getAllUsers();
// Si la función no lanza una excepción, la prueba falla
fail('Expected an error to be thrown');
} catch (error: any) {
// Verifica que axios.get haya sido llamado con la URL correcta
expect(axios.get).toHaveBeenCalledWith('http://localhost:8000/getAllUsers', {});

// Verifica que la función maneje correctamente el error
expect(error.message).toBe(errorMessage);
}
});

it('getUser() -> get user by username', async () => {
// Definir un nombre de usuario para buscar
const username = 'testuser';

// Configura el comportamiento simulado de axios.post
const responseData = { data: { username: 'testuser', email: 'test@example.com' } };
axios.post = jest.fn().mockResolvedValueOnce(responseData);

// Llama a la función que quieres probar
const result = await getUser(username);

// Verifica que axios.post haya sido llamado con la URL correcta y los datos de usuario correctos
expect(axios.post).toHaveBeenCalledWith('http://localhost:8000/getUser', { username });

// Verifica que la función devuelva los datos simulados
expect(result).toEqual(responseData.data);
});

it('should throw an error on failed request', async () => {
// Spy on the console.error function
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});

// Configure the mocked behavior of axios.post to return an error
const errorMessage = 'Request failed';
axios.post = jest.fn().mockRejectedValueOnce(new Error(errorMessage));


try {
await getUser('nonexistentuser');
} catch (error:any) {
// Verify that the error is caught and printed to the console
expect(consoleErrorSpy).toHaveBeenCalledWith('Error during retrieving the users', error);

// Verify that the exception is thrown
expect(error.message).toBe(errorMessage);
}

// Restore the original implementation of console.error
consoleErrorSpy.mockRestore();
});


it('update stats with incorrect data', async () => {
// Mock axios.post para simular una respuesta de error
axios.post = jest.fn().mockRejectedValueOnce(new Error('Request failed'));


const result = await updateStats(10, 8);

// Verifica que axios.post haya sido llamado con la URL correcta y los datos de usuario correctos
expect(axios.post).toHaveBeenCalledWith('http://localhost:8000/sumNormalStats', { username: null, questions_answered: 10, correctly_answered_questions: 8 });

// Verifica que la función devuelva false en caso de error
expect(result).toBe(false);
});


it('isLogged() -> should return true if there is a token in local storage', () => {
// Simula que hay un token en el almacenamiento local
localStorage.setItem('token', 'mockedToken');


const result = isLogged();

// Verifica que la función devuelva true
expect(result).toBe(true);

// Limpia el almacenamiento local después de la prueba
localStorage.removeItem('token');
});

it('isLogged() -> should return false if there is no token in local storage', () => {
localStorage.removeItem('token');

const result = isLogged();

// Verifica que la función devuelva false
expect(result).toBe(false);
});


});

0 comments on commit d1feb39

Please sign in to comment.