Skip to content

Commit

Permalink
Merge pull request #414 from Arquisoft/sergio
Browse files Browse the repository at this point in the history
Mejorando tests Login, UsersList y RankingList
  • Loading branch information
uo277310 authored Apr 28, 2024
2 parents 4d21180 + 5c739c3 commit c7bdd4e
Show file tree
Hide file tree
Showing 12 changed files with 448 additions and 96 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
node_modules
coverage
docs/build
docs/build
.idea/
6 changes: 6 additions & 0 deletions webapp/src/components/GameSettings.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import React, { useState, useEffect } from 'react';
import { Box, Typography, Slider, TextField, FormGroup, FormControlLabel, Checkbox, Tab } from '@mui/material';
import { TabContext, TabList, TabPanel } from '@mui/lab';
import PropTypes from 'prop-types';

const GameSettings = ({ setSettings, currentUser }) => {
const [isWarningVisible, setIsWarningVisible] = useState(false);
Expand Down Expand Up @@ -195,4 +196,9 @@ const GameSettings = ({ setSettings, currentUser }) => {
);
};

GameSettings.propTypes = {
setSettings: PropTypes.func.isRequired,
currentUser: PropTypes.string.isRequired,
};

export default GameSettings;
11 changes: 8 additions & 3 deletions webapp/src/components/GeneratedQuestionsList.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import PropTypes from 'prop-types';

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

const [listquestions, setListquestions] = useState([]);
const [sortColumn, setSortColumn] = useState(null);
Expand All @@ -22,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 Expand Up @@ -76,4 +77,8 @@ const GeneratedQuestionsList = () => {
);
};

GeneratedQuestionsList.propTypes = {
setError: PropTypes.func.isRequired,
};

export default GeneratedQuestionsList;
130 changes: 109 additions & 21 deletions webapp/src/components/GeneratedQuestionsList.test.js
Original file line number Diff line number Diff line change
@@ -1,43 +1,131 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import { render, screen, act } from '@testing-library/react';
import GeneratedQuestionsList from './GeneratedQuestionsList';
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';

jest.mock('axios');

const mockAxios = new MockAdapter(axios);

describe('GeneratedQuestionsList component', () => {
// Test for rendering the component and checking the main heading
test('renders GeneratedQuestionsList component and main heading', () => {
render(<GeneratedQuestionsList />);
beforeEach(() => {
axios.get.mockResolvedValue({
status: 200,
data: [
{
generatedQuestionBody: "¿A qué género literario pertenece 'Cinco horas con Mario'?",
correctAnswer: 'Narrativo'
},
{
generatedQuestionBody: "¿De qué grupo es la canción 'Vino Tinto'?",
correctAnswer: 'Estopa'
},
{
generatedQuestionBody: "¿Cuál es la capital de Portugal?",
correctAnswer: 'Lisboa'
},
{
generatedQuestionBody: "¿Quién escribió la novela 'El Extranjero'?",
correctAnswer: 'Albert Camus'
},
],
});
});

// Check if the main heading is in the document
test('renders GeneratedQuestionsList component and main heading', async () => {
await act( async () => {
render(<GeneratedQuestionsList setError={() => {}} />);
});
const heading = screen.getByRole('heading', { name: /Lista de preguntas/i });
expect(heading).toBeInTheDocument();
});

// Test for rendering the table
it('should display the table', () => {
render(<GeneratedQuestionsList />);

it('should display the table', async () => {
await act( async () => {
render(<GeneratedQuestionsList setError={() => {}} />);
});
const table = screen.getByRole('table');
expect(table).toBeInTheDocument();
});

// Test for rendering the table headers
test('renders table headers', () => {
render(<GeneratedQuestionsList />);

// Check if the table headers are in the document
test('renders table headers', async () => {
await act( async () => {
render(<GeneratedQuestionsList setError={() => {}} />);
});
const questionHeader = screen.getByRole('columnheader', { name: /Pregunta/i });
const answerHeader = screen.getByRole('columnheader', { name: /Respuesta Correcta/i });
expect(questionHeader).toBeInTheDocument();
expect(answerHeader).toBeInTheDocument();
});

// Test for rendering the table rows
test('renders table rows', () => {
render(<GeneratedQuestionsList />);
test('renders table rows', async () => {
await act( async () => {
render(<GeneratedQuestionsList setError={() => {}} />);
});
const tableRows = screen.getAllByRole('row');
expect(tableRows).not.toHaveLength(0);
});

test('should order questions by questionBody correctly', async () => {
await act(async () => {
render(<GeneratedQuestionsList setError={() => {}} />);
});

const questionBodyHeader = screen.getByRole('columnheader', { name: /Pregunta/i });

await act(async() => {
questionBodyHeader.click();
});

let rows = await screen.findAllByRole('row');

expect(rows[1]).toHaveTextContent("¿A qué género literario pertenece 'Cinco horas con Mario'?");
expect(rows[2]).toHaveTextContent("¿Cuál es la capital de Portugal?");
expect(rows[3]).toHaveTextContent("¿De qué grupo es la canción 'Vino Tinto'?");
expect(rows[4]).toHaveTextContent("¿Quién escribió la novela 'El Extranjero'?");

await act(async() => {
questionBodyHeader.click();
});

rows = await screen.findAllByRole('row');

// Check if the table rows are in the document
const tableRows = screen.getAllByRole('row');
expect(tableRows).not.toHaveLength(0);
});
expect(rows[4]).toHaveTextContent("¿A qué género literario pertenece 'Cinco horas con Mario'?");
expect(rows[3]).toHaveTextContent("¿Cuál es la capital de Portugal?");
expect(rows[2]).toHaveTextContent("¿De qué grupo es la canción 'Vino Tinto'?");
expect(rows[1]).toHaveTextContent("¿Quién escribió la novela 'El Extranjero'?");
});

test('should order questions by answer correctly', async () => {
await act(async () => {
render(<GeneratedQuestionsList setError={() => {}} />);
});

const answerHeader = screen.getByRole('columnheader', { name: /Respuesta Correcta/i });

await act(async() => {
answerHeader.click();
});

let rows = await screen.findAllByRole('row');

expect(rows[1]).toHaveTextContent("Albert Camus");
expect(rows[2]).toHaveTextContent("Estopa");
expect(rows[3]).toHaveTextContent("Lisboa");
expect(rows[4]).toHaveTextContent("Narrativo");


await act(async() => {
answerHeader.click();
});

rows = await screen.findAllByRole('row');

expect(rows[4]).toHaveTextContent("Albert Camus");
expect(rows[3]).toHaveTextContent("Estopa");
expect(rows[2]).toHaveTextContent("Lisboa");
expect(rows[1]).toHaveTextContent("Narrativo");
});

});
18 changes: 8 additions & 10 deletions webapp/src/components/Login.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,16 +45,14 @@ const Login = ({ setLogged }) => {
try {
const response = await axios.post(`${apiEndpoint}/login`, { username, password });
const { createdAt: userCreatedAt } = response.data;
const usersResponse = await axios.get(`${apiEndpoint}/getAllUsers`);
const users = usersResponse.data;

await axios.get(`${apiEndpoint}/getAllUsers`);
setCreatedAt(userCreatedAt);
setLoginSuccess(true);
setLogged();
setLoading(true);

// Envía todos los nombres de usuario en una sola solicitud
await axios.post(`${apiEndpoint}/createUserRank`, { username });
// Envía todos los nombres de usuario en una sola solicitud
await axios.post(`${apiEndpoint}/createUserRank`, { username });

setLoading(false);
setOpenSnackbar(true);
Expand All @@ -64,7 +62,7 @@ const Login = ({ setLogged }) => {
} else if (error.request) {
setError('No response from server. Please try again later.');
} else {
setError('An unexpected error occurred.');
setError('An unexpected error occurred');
}
}
};
Expand Down Expand Up @@ -142,10 +140,10 @@ const Login = ({ setLogged }) => {
{showComponent === 'game' &&
<Game username={username} totalQuestions={settings.numberQuestions} timeLimit={totalTime} themes={settings.themes}/>
}
{showComponent === 'userList' && <UsersList />}
{showComponent === 'questionList' && <GeneratedQuestionsList />}
{showComponent === 'recordList' && <RecordList username={username} />}
{showComponent === 'rankingList' && <RankingList />}
{showComponent === 'userList' && <UsersList setError={setError} />}
{showComponent === 'questionList' && <GeneratedQuestionsList setError={setError} />}
{showComponent === 'recordList' && <RecordList username={username} setError={setError} />}
{showComponent === 'rankingList' && <RankingList setError={setError} />}
{showComponent === 'settings' && <GameSettings setSettings={setSettings} currentUser={username} />}
{showComponent === 'login' && (
<div>
Expand Down
Loading

0 comments on commit c7bdd4e

Please sign in to comment.