Skip to content

Commit

Permalink
#29 Mas tests unitarios en el frontend
Browse files Browse the repository at this point in the history
  • Loading branch information
AlvaroGlezC committed Apr 27, 2024
1 parent a8ba435 commit 0cb68fa
Show file tree
Hide file tree
Showing 11 changed files with 232 additions and 39 deletions.
16 changes: 8 additions & 8 deletions syg-frontend/src/backend/dataSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,21 @@ export function getUsers(): Promise<User[]> {
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
throw new Error('There has been an error in the search for users through the api');
}
return response.json();
})
}

export function getUser(id: string): Promise<User> {
return fetch(`http://localhost:8080/user/user?id=${id}`, {
return fetch(`http://localhost:8080/user/userId?id=${id}`, {
headers: {
Authorization: `Bearer ${keycloak.token}`
}
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
throw new Error(`An error occurred when searching for the user with id ${id} through the api.`);
}
return response.json();
})
Expand All @@ -40,7 +40,7 @@ export function registryUser(user: User): Promise<User> {
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
throw new Error('An error occurred while registering a user through the api');
}
return response.json();
})
Expand All @@ -58,7 +58,7 @@ export function updateUser(user: User): Promise<User> {
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
throw new Error('An error occurred when updating a users data through the api');
}
return response.json();
})
Expand All @@ -72,7 +72,7 @@ export function getQuestions():Promise<Question[]> {
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
throw new Error('An error occurred when getting the questions with their answers through the api');
}
return response.json();
})
Expand All @@ -86,7 +86,7 @@ export function getQuestionsByCategory(categoryId: number):Promise<Question[]> {
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
throw new Error('An error occurred when getting the questions with their answers according to their category through the api.');
}
return response.json();
})
Expand All @@ -100,7 +100,7 @@ export function getCategories():Promise<Category[]> {
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
throw new Error('An error occurred when getting the categories through the api');
}
return response.json();
})
Expand Down
8 changes: 4 additions & 4 deletions syg-frontend/src/components/aside/Aside.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@ const Aside: React.FC<AsideProps> = (props: AsideProps) => {
return (
<div id='syg-aside-container' data-testid='syg-aside-container'>
<div id='syg-aside-navigation-menu' data-testid='syg-aside-navigation-menu'>
{props.elements.map((element) => (
<div className='syg-aside-navigation-menu-element' onClick={()=>handleOnClickAsideElement(element.onClickAsideElement)}>
{element.icon}
<div className='syg-aside-navigation-menu-element-text'>
{props.elements.map((element, index) => (
<div key={'syg-aside-navigation-menu-element' + index} className='syg-aside-navigation-menu-element' onClick={()=>handleOnClickAsideElement(element.onClickAsideElement)}>
{element.icon}
<div key={'syg-aside-navigation-menu-element-text' + index} className='syg-aside-navigation-menu-element-text'>
{t(`aside.${element.text}`)}
</div>
</div>
Expand Down
119 changes: 119 additions & 0 deletions syg-frontend/src/modules/game/Game.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import { screen, render, fireEvent, waitFor } from "@testing-library/react"
import Game from "./Game"
import i18n from '../../translation/i18n';
import { getUser, getCategories, getQuestions, updateUser } from '../../backend/dataSource';
import { MemoryRouter } from "react-router-dom";

describe('Game', () => {
const mockUser = {
id: '123',
name: 'Alvaro',
totalGames: 1,
correctAnswers: 8,
inCorrectAnswers: 24,
totalQuestionAnswered: 15,
lastCategoryPlayed: 'Deportes',
};

const mockCategories = [
{ id: '1', name: 'Deportes' },
{ id: '2', name: 'Ciencia' },
];

const mockQuestions = [
{
text: '¿Cuál es el planeta más grande?',
timeLimit: 10,
answers: [
{ text: 'Júpiter', isCorrect: true },
{ text: 'Saturno', isCorrect: false },
{ text: 'Tierra', isCorrect: false },
{ text: 'Marte', isCorrect: false },
],
},
];

beforeAll(() => {
i18n.changeLanguage('Spain');
});

// beforeEach(() => {
// // Mockear las funciones asíncronas
// jest.mock('../../backend/dataSource', () => ({
// getUser: jest.fn().mockResolvedValue(mockUser),
// getCategories: jest.fn().mockResolvedValue(mockCategories),
// getQuestions: jest.fn().mockResolvedValue(mockQuestions)
// }));
// });

test('Game renders correctly', () => {
render(<Game/>)

const element = screen.getByTestId('syg-game-container')
expect(element).toBeInTheDocument();
})

test('Header components renders correctly', () => {
render(<Game/>)

const gameContent = screen.getByTestId('syg-game-content')
expect(gameContent).toBeInTheDocument();

// const gameStart = screen.getByTestId('syg-game-content-start-game')
// expect(gameStart).toBeInTheDocument();

// const gameStartOptions = screen.getByTestId('syg-game-content-start-game-options')
// expect(gameStartOptions).toBeInTheDocument();

})


// test('starts game and answers questions', async () => {
// render(
// <MemoryRouter>
// <Game />
// </MemoryRouter>
// );

// // Esperar a que se carguen categorías
// await waitFor(() => {
// expect(screen.getByText('Deportes')).toBeInTheDocument();
// });

// // Iniciar el juego
// fireEvent.click(screen.getByText('Deportes')); // Elige una categoría para comenzar

// await waitFor(() => {
// expect(screen.getByText('¿Cuál es el planeta más grande?')).toBeInTheDocument();
// });

// // Responder una pregunta
// fireEvent.click(screen.getByText('Júpiter')); // Respuesta correcta

// await waitFor(() => {
// expect(updateUser).toHaveBeenCalled(); // Verificar que `updateUser` fue llamado
// });
// });

// test('finishes the game and shows results', async () => {
// render(
// <MemoryRouter>
// <Game />
// </MemoryRouter>
// );

// // Iniciar el juego
// fireEvent.click(screen.getByText('Deportes')); // Elegir una categoría

// await waitFor(() => {
// expect(screen.getByText('¿Cuál es el planeta más grande?')).toBeInTheDocument();
// });

// // Responder todas las preguntas y terminar el juego
// fireEvent.click(screen.getByText('Júpiter')); // Primera respuesta
// await waitFor(() => {
// expect(screen.getByText('game.results.title')).toBeInTheDocument(); // Verificar que muestra los resultados
// });
// });

})
12 changes: 6 additions & 6 deletions syg-frontend/src/modules/game/Game.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -115,13 +115,13 @@ const Game: React.FC = () => {
}

return (
<div id='syg-game-container'>
<div id='syg-game-container' data-testid='syg-game-container'>
<Header info='game' />
<div id='syg-game-content'>
<div id='syg-game-content' data-testid='syg-game-content'>
{categories.length > 0 && (questions === undefined || questions.length < 1) ? (
<div id='syg-game-content-start-game'>
<h2>{t('game.mode.title')}</h2>
<div id='syg-game-content-start-game-options'>
<div id='syg-game-content-start-game' data-testid='syg-game-content-start-game'>
<h2 >{t('game.mode.title')}</h2>
<div id='syg-game-content-start-game-options' data-testid='syg-game-content-start-game-options'>
<Button
className='syg-game-start-game-button'
onClick={() => handleStartGame()}
Expand Down Expand Up @@ -165,7 +165,7 @@ const Game: React.FC = () => {
</div>
):(
<div id='syg-game-finish'>
<h2>{t('game.results.tittle')}</h2>
<h2>{t('game.results.title')}</h2>
<Chart
correctAnswers={totalCorrectAnswers}
incorrectAnswers={totalIncorrectAnswers}
Expand Down
58 changes: 58 additions & 0 deletions syg-frontend/src/modules/game/StadisticsGame.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { screen, render, fireEvent } from "@testing-library/react"
import StadisticsGame from "./StadisticsGame"
import i18n from '../../translation/i18n';

describe('StadisticsGame', () => {
beforeAll(() => {
i18n.changeLanguage('Spain');
});

test('StadisticsGame renders correctly', () => {
render(<StadisticsGame correctAnswers={10} incorrectAnswers={20}/>)

const element = screen.getByTestId('stadistic-game-container')
expect(element).toBeInTheDocument();
})

test('StadisticsGame components renders correctly', () => {
render(<StadisticsGame correctAnswers={10} incorrectAnswers={20}/>)

const stadisticgameCorrect = screen.getByTestId('stadistic-game-correct')
expect(stadisticgameCorrect).toBeInTheDocument();

const stadisticgameCorrectInfo = screen.getByTestId('stadistic-game-correct-info')
expect(stadisticgameCorrectInfo).toBeInTheDocument();

const stadisticgameCorrectBar = screen.getByTestId('stadistic-game-correct-bar')
expect(stadisticgameCorrectBar).toBeInTheDocument();

const stadisticgameInCorrect = screen.getByTestId('stadistic-game-incorrect')
expect(stadisticgameInCorrect).toBeInTheDocument();

const stadisticgameInCorrectInfo = screen.getByTestId('stadistic-game-incorrect-info')
expect(stadisticgameInCorrectInfo).toBeInTheDocument();

const stadisticgameInCorrectBar = screen.getByTestId('stadistic-game-incorrect-bar')
expect(stadisticgameInCorrectBar).toBeInTheDocument();
})

test('StadisticsGame correct aswers tests', () => {
render(<StadisticsGame correctAnswers={10} incorrectAnswers={20}/>)

const stadisticgameCorrectInfo = screen.getByTestId('stadistic-game-correct-info')
expect(stadisticgameCorrectInfo).toHaveTextContent("Respuestas correctas:");

const stadisticgameCorrectBar = screen.getByTestId('stadistic-game-correct-bar')
expect(stadisticgameCorrectBar).toHaveTextContent("10");
})

test('StadisticsGame incorrect aswers tests', () => {
render(<StadisticsGame correctAnswers={10} incorrectAnswers={20}/>)

const stadisticgameInCorrectInfo = screen.getByTestId('stadistic-game-incorrect-info')
expect(stadisticgameInCorrectInfo).toHaveTextContent("Respuestas incorrectas:");

const stadisticgameInCorrectBar = screen.getByTestId('stadistic-game-incorrect-bar')
expect(stadisticgameInCorrectBar).toHaveTextContent("20");
})
})
14 changes: 7 additions & 7 deletions syg-frontend/src/modules/game/StadisticsGame.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@ function Chart(props: ChartAnswersProps) {
const { t } = useTranslation();

return (
<Paper id='stadistic-game-container'>
<div id='stadistic-game-correct'>
<span>{t('game.results.correctAnswers')}:</span>
<div id='stadistic-game-correct-bar' style={{ width: `${props.correctAnswers * 10}px`}}>{props.correctAnswers}</div>
<Paper id='stadistic-game-container' data-testid='stadistic-game-container'>
<div id='stadistic-game-correct' data-testid='stadistic-game-correct'>
<span data-testid='stadistic-game-correct-info'>{t('game.results.correctAnswers')}:</span>
<div id='stadistic-game-correct-bar' style={{ width: `${props.correctAnswers * 10}px`}} data-testid='stadistic-game-correct-bar'>{props.correctAnswers}</div>
</div>
<div id='stadistic-game-incorrect'>
<span>{t('game.results.incorrectAnswers')}:</span>
<div id='stadistic-game-incorrect-bar' style={{ width: `${props.incorrectAnswers * 10}px`}}>{props.incorrectAnswers}</div>
<div id='stadistic-game-incorrect' data-testid='stadistic-game-incorrect'>
<span data-testid='stadistic-game-incorrect-info'>{t('game.results.incorrectAnswers')}:</span>
<div id='stadistic-game-incorrect-bar' style={{ width: `${props.incorrectAnswers * 10}px`}} data-testid='stadistic-game-incorrect-bar'>{props.incorrectAnswers}</div>
</div>
</Paper>
);
Expand Down
2 changes: 1 addition & 1 deletion syg-frontend/src/modules/historic/Historic.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ const Historic: React.FC = () => {
<div id='syg-historic-container' data-testid='syg-historic-container'>
<Header info='historics' />
<div id='syg-historic-content' data-testid='syg-historic-content'>
<span id='syg-historic-user-name' data-testid='syg-historic-user-name'> {t('historics.title')}: <i data-testid='syg-historic-user-active-name'>{userActive?.name}</i></span>
<span id='syg-historic-user-name' data-testid='syg-historic-user-name'> {t('historics.title')}</span>
<div id='syg-historic-user-info' data-testid='syg-historic-user-info'>
<div id='primary-info' data-testid='syg-header-primary-info'>
<UserInfoCard
Expand Down
9 changes: 1 addition & 8 deletions syg-frontend/src/modules/historic/Historics.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,6 @@ describe('Historic', () => {
render(<Historic/>)

const userNameHistoric = screen.getByTestId('syg-historic-user-name')
expect(userNameHistoric).toHaveTextContent("Datos de juego de:");
})

test('Historic get user active', () => {
render(<Historic/>)

const userNameHistoric = screen.getByTestId('syg-historic-user-active-name')
expect(userNameHistoric).toHaveTextContent("");
expect(userNameHistoric).toHaveTextContent("Datos de juego");
})
})
23 changes: 23 additions & 0 deletions syg-frontend/src/modules/home/Home.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { screen, render, fireEvent } from "@testing-library/react"
import Home from "./Home"
import i18n from '../../translation/i18n';

describe('Home', () => {
beforeAll(() => {
i18n.changeLanguage('Spain');
});

test('Home renders correctly', () => {
render(<Home/>)

const element = screen.getByTestId('syg-home-container')
expect(element).toBeInTheDocument();
})

test('Home components renders correctly', () => {
render(<Home/>)

const homeContent = screen.getByTestId('syg-home-content')
expect(homeContent).toBeInTheDocument();
})
})
4 changes: 2 additions & 2 deletions syg-frontend/src/modules/home/Home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import './Home.scss';

const Home: React.FC = () => {
return (
<div id='syg-home-container'>
<div id='syg-home-container' data-testid='syg-home-container'>
<Header info='Home' />
<div id='syg-home-content'>
<div id='syg-home-content' data-testid='syg-home-content'>
PANTALLA HOME
</div>
</div>
Expand Down
Loading

0 comments on commit 0cb68fa

Please sign in to comment.