Skip to content

Commit

Permalink
Mejorando coverage componentes
Browse files Browse the repository at this point in the history
  • Loading branch information
uo287627 committed Apr 25, 2024
1 parent 7cb1457 commit e77cd55
Show file tree
Hide file tree
Showing 6 changed files with 85 additions and 25 deletions.
6 changes: 3 additions & 3 deletions webapp/src/components/GeneratedQuestionsList.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import React, { useState, useEffect } from 'react';
import axios from 'axios';
//import { Container, Typography, TextField, Button, Snackbar } from '@mui/material';

const GeneratedQuestionsList = () => {
const GeneratedQuestionsList = ({setError}) => {

const [listquestions, setListquestions] = useState([]);
const [sortColumn, setSortColumn] = useState(null);
Expand All @@ -23,10 +23,10 @@ const GeneratedQuestionsList = () => {
setListquestions(qList);

} else {
console.error('Error obteniendo la lista de preguntas generadas');
setError('Error obteniendo la lista de preguntas generadas');
}
} catch (error) {
console.error('Error obteniendo la lista de preguntas generadas:', error);
setError('Error obteniendo la lista de preguntas generadas:', error);
}
};

Expand Down
6 changes: 3 additions & 3 deletions webapp/src/components/#.js
Original file line number Diff line number Diff line change
Expand Up @@ -148,10 +148,10 @@ const Login = ({ setLogged }) => {
{showComponent === 'game' &&
<Game username={username} totalQuestions={settings.numberQuestions} timeLimit={totalTime} themes={settings.themes}/>
}
{showComponent === 'userList' && <UsersList />}
{showComponent === 'questionList' && <GeneratedQuestionsList />}
{showComponent === 'userList' && <UsersList errorHanndler={setError} />}
{showComponent === 'questionList' && <GeneratedQuestionsList errorHanndler={setError} />}
{showComponent === 'recordList' && <RecordList username={username} />}
{showComponent === 'rankingList' && <RankingList />}
{showComponent === 'rankingList' && <RankingList errorHanndler={setError} />}
{showComponent === 'settings' && <GameSettings setSettings={setSettings} currentUser={username} />}
{showComponent === 'login' && (
<div>
Expand Down
6 changes: 3 additions & 3 deletions webapp/src/components/RankingList.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React, { useState, useEffect } from 'react';
import axios from 'axios';

const RankingList = () => {
const RankingList = ({setError}) => {
const [listUsers, setListUsers] = useState([]);
const [sortColumn, setSortColumn] = useState('porcentajeAciertos');
const [sortOrder, setSortOrder] = useState('desc');
Expand All @@ -23,10 +23,10 @@ const RankingList = () => {
const sortedUsers = [...uList].sort((a, b) => b.porcentajeAciertos - a.porcentajeAciertos);
setTopThreeUsers(sortedUsers.slice(0, 3));
} else {
console.error('Error obteniendo la lista de usuarios');
setError('Error obteniendo la lista de usuarios');
}
} catch (error) {
console.error('Error obteniendo la lista de usuarios:', error);
setError('Error obteniendo la lista de usuarios: ', error);
}
};

Expand Down
64 changes: 64 additions & 0 deletions webapp/src/components/RankingList.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import React from 'react';
import { render, screen, waitFor, act } from '@testing-library/react';
import RankingList from './RankingList';
import axios from 'axios';
import { before } from 'node:test';

jest.mock('axios');

Expand Down Expand Up @@ -120,6 +121,40 @@ describe('RankingList', () => {

});

test('show users ordered by "username" correctly', async () => {
await act(async () => {
render(<RankingList />);
});
const usernameHeader = screen.getByRole('columnheader', { name: /Nombre de Usuario/i });

await act(async() => {
usernameHeader.click(); // DESC
});

// We wait for the users to be loaded and the table to be updated
let rows = await screen.findAllByRole('row');

// We check if the first row is the one with the username 'troll'
expect(rows[4]).toHaveTextContent('manuel');
expect(rows[3]).toHaveTextContent('maría');
expect(rows[2]).toHaveTextContent('pedro');
expect(rows[1]).toHaveTextContent('troll');

await act(async() => {
usernameHeader.click(); // ASC
});

// We wait for the users to be loaded and the table to be updated
rows = await screen.findAllByRole('row');

// We check if the first row is the one with the username 'manuel'
expect(rows[1]).toHaveTextContent('manuel');
expect(rows[2]).toHaveTextContent('maría');
expect(rows[3]).toHaveTextContent('pedro');
expect(rows[4]).toHaveTextContent('troll');

});

test('show users ordered by "porcentajeAciertos" correctly', async () => {
await act(async () => {
render(<RankingList />);
Expand Down Expand Up @@ -255,4 +290,33 @@ describe('RankingList', () => {

}); // fin tests correctos

describe('failing requests', () => {
test('should display an error message when the request fails', async () => {
await act(async () => {
render(<RankingList />);
});

// simulate a failed request
mockAxios.onPost('http://localhost:8000/obtainRank').reply(500, { error: 'Internal Server Error' });

// Check if the table headers are in the document
expect(screen.queryByText("Ranking")).toBeInTheDocument();
expect(screen.getByText(/Nombre de Usuario/i)).toBeInTheDocument();
expect(screen.queryAllByText(/Porcentaje de Aciertos/i)).not.toHaveLength(0);
expect(screen.getByText(/Preguntas Correctas/i)).toBeInTheDocument();
expect(screen.getByText(/Preguntas Falladas/i)).toBeInTheDocument();
expect(screen.getByText(/Número de Partidas/i)).toBeInTheDocument();

// and no users rows are shown
const rows = await screen.findAllByRole('row');
expect(rows.length).toBe(1);

// Wait for the error Snackbar to be open
await waitFor(() => {
expect(screen.getByText(/Error: Internal Server Error/i)).toBeInTheDocument();
});
});

}); // fin tests fallidos

});
7 changes: 3 additions & 4 deletions webapp/src/components/UsersList.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import React, { useState, useEffect } from 'react';
import axios from 'axios';
//import { Container, Typography, TextField, Button, Snackbar } from '@mui/material';

const UsersList = () => {
const UsersList = ({ setError }) => {

const [listUsers, setListUsers] = useState([]);

Expand All @@ -25,13 +25,12 @@ const UsersList = () => {
setListUsers(uList);

} else {
console.error('Error obteniendo la lista de usurios');
setError('Error obteniendo la lista de usurios');
}
} catch (error) {
console.error('Error obteniendo la lista de usurios:', error);
setError(`Error obteniendo la lista de usurios: ${error}`);
}
};

fetchUsers();
}, [apiEndpoint]);

Expand Down
21 changes: 9 additions & 12 deletions webapp/src/components/UsersList.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,22 +127,14 @@ describe('UsersList', () => {


describe('failing requests', () => {
beforeEach(() => {
axios.get.mockRejectedValue({
response: {
status: 500,
data: {
error: 'Internal Server Error'
},
},
});
});

it('users list is empty (only headers are shown) when petition fails', async () => {
test('users list is empty (only headers are shown) when petition fails', async () => {
await act(async () => {
render(<UsersList />);
});

// simulate a failed request
mockAxios.onPost('http://localhost:8000/getAllUsers').reply(500, { error: 'Internal Server Error' });

// Check if the table headers are in the document
const usernameHeader = screen.getByRole('columnheader', { name: /Nombre de Usuario/i });
const createdAtHeader = screen.getByRole('columnheader', { name: /Fecha de Registro/i });
Expand All @@ -153,6 +145,11 @@ describe('UsersList', () => {
// and no users rows are shown
const rows = await screen.findAllByRole('row');
expect(rows.length).toBe(1);

// Wait for the error Snackbar to be open
await waitFor(() => {
expect(screen.getByText(/Error: Internal Server Error/i)).toBeInTheDocument();
});
});
});

Expand Down

0 comments on commit e77cd55

Please # to comment.