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 4c6d7a0 + 6a51f94 commit 05429e7
Show file tree
Hide file tree
Showing 9 changed files with 437 additions and 104 deletions.
84 changes: 79 additions & 5 deletions webapp/src/components/Game/Game.test.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,87 @@
import { render, screen } from '@testing-library/react';
import { render, fireEvent ,screen, waitFor } from '@testing-library/react';
import React from 'react';
import Game from './Game';
import Game, { formatNumberWithDots} from './Game';
import { act } from 'react-dom/test-utils';

const wait = (milliseconds: number) => {
return new Promise<void>((resolve) => {
setTimeout(resolve, milliseconds);
});
};

jest.mock("../../services/question-service", () => {
return {
getHardString : () => 'hard',
getQuestionsFromApi: () => {
return Promise.resolve([
{
text: '¿Cuál es la capital de España?',
correctAnswer: 0,
answers: ['Madrid','Barcelona', 'Sevilla', 'Valencia'],
wikiLink: ''
},
{
text: '¿Cuál es la capital de Francia?',
correctAnswer: 0,
answers: ['Paris','Barcelona', 'Sevilla', 'Valencia'],
wikiLink: ''
}
]);
}
}
});

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


it('should render the game',async () => {
await act( async () => {
render(<Game difficulty='easy'/>);
});
expect(screen.getByTestId('game-component')).toBeInTheDocument();
});

describe('Game component', () => {
it('should render the game', () => {
render( <Game difficulty='easy'/> );
it('should render the game in hard mode',async () => {
await act( async () => {
render(<Game difficulty='hard'/>);
});
expect(screen.getByTestId('game-component')).toBeInTheDocument();
});

it('should go to the next question', async () => {
await act( async () => {
render(<Game difficulty='easy'/>);
});

expect(screen.getByTestId('game-container')).toBeInTheDocument();

expect(screen.getByText('Madrid')).toBeInTheDocument();
fireEvent.click(screen.getByText('Madrid'));

await wait(4000);
expect(screen.getByText('Paris')).toBeInTheDocument();

});

it('format a number with the dots', () => {
const shortNumber = '700';
expect(formatNumberWithDots(shortNumber)).toBe('700');

const number = '100000';
expect(formatNumberWithDots(number)).toBe('100.000');
});

//mockear la llegada de preguntas de la api
it('should display the question and answers when the questions arrive', async () => {

await act( async () => {
render(<Game difficulty='easy'/>);
});

expect(screen.getByText('Madrid')).toBeInTheDocument();
});




});
41 changes: 20 additions & 21 deletions webapp/src/components/Game/Game.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,30 @@ import AnswerPanel from "./AnswerPanel";
import GameOver from "./GameOver";
import Counter from "./Counter";
import Countdown from "./Countdown";
import {getHardString, Question as questionType} from "../../services/question-service";
import { getQuestionsFromApi } from "../../services/question-service";
import {getHardString, getQuestionsFromApi, Question as questionType} from "../../services/question-service";
import { updateStats } from "../../services/auth-service";

type Props = {
difficulty: string;
};

export const formatNumberWithDots = (str : string) => {

if (str.length < 5 || str.includes('.')) {
return str;
}
let result = '';
for (let i = str.length - 1, count = 0; i >= 0; i--, count++) {
result = str[i] + result;
if (count % 3 === 2 && i !== 0) {
result = '.' + result;
}
}

return result;
};


export default function Game(props: Props) {
const [answered, setAnswered] = useState(false);
const [loading, setLoading] = useState(false);
Expand All @@ -32,28 +48,11 @@ export default function Game(props: Props) {

useEffect(() => {
getQuestionsFromApi().then((questions : questionType[]) => {

setQuestions(questions)
setLoadingData(false);
})
}, []);

function formatNumberWithDots(str : string) : string {

if (str.length < 5 || str.includes('.')) {
return str;
}
let result = '';
for (let i = str.length - 1, count = 0; i >= 0; i--, count++) {
result = str[i] + result;
if (count % 3 === 2 && i !== 0) {
result = '.' + result;
}
}

return result;
}

const goToNextQuestion = () => {
setCount(questionTime);
setCorrectSelected(false);
Expand Down Expand Up @@ -95,15 +94,15 @@ export default function Game(props: Props) {

if (questionCount === 10) {
updateStats(questionCount, score/10);
return <GameOver answers={answerSelected} questions={questions} finalMessage="Game Over" />;
return <GameOver data-testid="game-over-component" answers={answerSelected} questions={questions} finalMessage="Game Over" />;
}



return (
<div className="h-4/5" data-testid="game-component">
{loadingdata ? <h1>Loading...</h1> :
<div id='mainContainer' className='flex flex-col h-full text-text'>
<div data-testid="game-container" id='mainContainer' className='flex flex-col h-full text-text'>
<div id='pregunta' className='h-1/2 flex-1'>
<div className="flex justify-between">
<text className='text-white text-xl font-bold p-4'> {questionCount+1}/{questions.length} </text>
Expand Down
144 changes: 123 additions & 21 deletions webapp/src/components/Game/Trivia/TriviaGame.test.tsx
Original file line number Diff line number Diff line change
@@ -1,36 +1,84 @@
import React from 'react';
import { render, fireEvent, waitFor, screen } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import { TriviaGame } from './TriviaGame';
import { TriviaGame, formatNumberWithDots, isNumber, generateDiceRandomNumber, getQuestion} from './TriviaGame';
import { getEasyString, getHardString } from '../../../services/question-service';

// jest.mock('./trivia_service', () => ({
// getSportQuestions: jest.fn().mockResolvedValue({
// text: 'Sports question',
// answers: ['answer1', 'answer2', 'answer3', 'answer4'],
// correctAnswer: 0,
// wikiLink: ''
// }),
// getScienceQuestions: jest.fn().mockResolvedValue({
// question: 'Science question',
// answers: ['answer1', 'answer2', 'answer3', 'answer4'],
// correctAnswer: 0,
// wikiLink: ''
// }),
// getHistoryQuestions: jest.fn().mockResolvedValue({
// question: 'History question',
// answers: ['answer1', 'answer2', 'answer3', 'answer4'],
// correctAnswer: 0,
// wikiLink: ''
// }),
// getGeographyQuestions: jest.fn().mockResolvedValue({
// question: 'Geography question',
// answers: ['answer1', 'answer2', 'answer3', 'answer4'],
// correctAnswer: 0,
// wikiLink: ''
// }),
// getEntertainmentQuestions: jest.fn().mockResolvedValue({
// question: 'Entertainment question',
// answers: ['answer1', 'answer2', 'answer3', 'answer4'],
// correctAnswer: 0,
// wikiLink: ''
// }),
// }));

jest.mock('./trivia_service', () => ({
getSportQuestions: jest.fn().mockResolvedValue({
question: 'Sport question',
answers: ['answer1', 'answer2', 'answer3', 'answer4'],
correctAnswer: 0,
}),
getScienceQuestions: jest.fn().mockResolvedValue({
question: 'Science question',
getSportQuestions: () => {
return ({
text: 'Sports question',
correctAnswer: 0,
answers: ['answer1', 'answer2', 'answer3', 'answer4'],
wikiLink: ''
});
},
getScienceQuestions: ()=>{
return ({
text: 'Science question',
answers: ['answer1', 'answer2', 'answer3', 'answer4'],
correctAnswer: 0,
}),
getHistoryQuestions: jest.fn().mockResolvedValue({
question: 'History question',
wikiLink: ''
}
)},
getHistoryQuestions: ()=>{
return ({
text: 'History question',
answers: ['answer1', 'answer2', 'answer3', 'answer4'],
correctAnswer: 0,
wikiLink: ''
})},
getGeographyQuestions: ()=>{
return ({
text: 'Geography question',
answers: ['answer1', 'answer2', 'answer3', 'answer4'],
correctAnswer: 0,
}),
getGeographyQuestions: jest.fn().mockResolvedValue({
question: 'Geography question',
wikiLink: ''
})},
getEntertainmentQuestions: ()=>{
return ({
text: 'Entertainment question',
answers: ['answer1', 'answer2', 'answer3', 'answer4'],
correctAnswer: 0,
}),
getEntertainmentQuestions: jest.fn().mockResolvedValue({
question: 'Entertainment question',
answers: ['answer1', 'answer2', 'answer3', 'answer4'],
correctAnswer: 0,
}),
}));
wikiLink: ''
})},
}));




jest.mock('./categories', () => ({
getCategoryColor: jest.fn(),
Expand All @@ -52,4 +100,58 @@ describe('TriviaGame', () => {
fireEvent.click(rollButton);
await waitFor(() => expect(screen.getByText(/Category:/)).toBeInTheDocument());
});

it('format a number with the dots', () => {
const shortNUmber = '700';
expect(formatNumberWithDots(shortNUmber)).toBe('700');

const number = '700000';
expect(formatNumberWithDots(number)).toBe('700.000');
});

it('returns if a string is a number', () => {
const number = '100000';
expect(isNumber(number)).toBe(true);

const notNumber = 'not a number';
expect(isNumber(notNumber)).toBe(false);
});

it('generates a random number between 1 and 5', () => {
let number = generateDiceRandomNumber();
expect(number).toBeGreaterThanOrEqual(1);
expect(number).toBeLessThanOrEqual(5);

number = generateDiceRandomNumber();
expect(number).toBeGreaterThanOrEqual(1);
expect(number).toBeLessThanOrEqual(5);
});

it('should return a question based on category', async () => {

const sportQuestion = await getQuestion('Sport');

expect(sportQuestion.text).toBe('Sports question');
expect(sportQuestion.answers).toEqual(['answer1', 'answer2', 'answer3', 'answer4']);
expect(sportQuestion.correctAnswer).toBe(0);
expect(sportQuestion.wikiLink).toBe('');

const scienceQuestion = await getQuestion('Science');
expect(scienceQuestion.text).toBe('Science question');

const historyQuestion = await getQuestion('History');
expect(historyQuestion.text).toBe('History question');

const geographyQuestion = await getQuestion('Geography');
expect(geographyQuestion.text).toBe('Geography question');

const entertainmentQuestion = await getQuestion('Entertainment');
expect(entertainmentQuestion.text).toBe('Entertainment question');

//default is sports
const defaultQuestion = await getQuestion('Other');
expect(defaultQuestion.text).toBe('Sports question');

});

});
Loading

0 comments on commit 05429e7

Please sign in to comment.