Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question fetching time significantly reduced and now player cannot answer if time is not running #125

Merged
merged 6 commits into from
Apr 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 21 additions & 4 deletions questionservice/question-service.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ jest.spyOn(global, 'fetch').mockImplementation(() => {
let result = { results: {bindings: []} }
for(let i=1;i<=100;i++){
//Simulating there is maximum number of repeated itemLabels (between the valid ones)
result.results.bindings.push({itemLabel: {value: "itemName1"} , image:{value: "imageUrl1_"+i}})
imgsToAssociatesMap.set("imageUrl1_"+i, "itemName1")
result.results.bindings.push({itemLabel: {value: "itemName"+i} , image:{value: "imageUrl1_"+i}})
imgsToAssociatesMap.set("imageUrl1_"+i, "itemName"+i)
}
for(let i=101;i<=195;i++){
//Simulating there are invalid itemLabels
Expand Down Expand Up @@ -113,7 +113,7 @@ describe('Question Service', () => {
});

//Test /imgs/answer endpoint (Incorrect answer)
it('should inform the answer is incorrect and what is the element associated to the answer', async () => {
it('should inform the answer is incorrect and what is the correct answer if answering incorrectly', async () => {
//First I ask a question
const response = await request(app).get('/imgs/foods/question');
regex = new RegExp(`Which of the following images corresponds to (\\w+)\\?`);
Expand All @@ -135,7 +135,24 @@ describe('Question Service', () => {
.set('Content-Type', 'application/json')
.send({answer:incorrectImageAnswer, question:question, username:"username", category:"foods"})
expect(responseAnswer.body.correct).toBe("false")
expect(responseAnswer.body.associate).toBe(imgsToAssociatesMap.get(incorrectImageAnswer))
expect(responseAnswer.body.correctImg).toBe([...imgsToAssociatesMap].find(([key, val]) => val == correctAnswerLabel)[0])
});

//Test /imgs/answer endpoint (Timeout)
it('should inform the answer is incorrect and what is the correct answer if a timeout happens', async () => {
//First I ask a question
const response = await request(app).get('/imgs/foods/question');
regex = new RegExp(`Which of the following images corresponds to (\\w+)\\?`);
const match = response.body.question.match(regex);
const correctAnswerLabel = match && match[1];

question = response.body.question
const responseAnswer = await request(app)
.post("/imgs/answer")
.set('Content-Type', 'application/json')
.send({answer:"TimeOut1234;", question:question, username:"username", category:"foods"})
expect(responseAnswer.body.correct).toBe("false")
expect(responseAnswer.body.correctImg).toBe([...imgsToAssociatesMap].find(([key, val]) => val == correctAnswerLabel)[0])
});
});

Expand Down
4 changes: 2 additions & 2 deletions webapp/src/components/Login.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ describe('Login component', () => {

const usernameInput = screen.getByLabelText(/Username/i);
const passwordInput = screen.getByLabelText(/Password/i);
const loginButton = screen.getByRole('button', { name: /Login/i });
const loginButton = screen.getByRole('button', { name: /Log In/i });
const mock = jest.fn();
jest.mock('react-router-dom', () => ({
useNavigate: () => mock,
Expand Down Expand Up @@ -73,7 +73,7 @@ describe('Login component', () => {

const usernameInput = screen.getByLabelText(/Username/i);
const passwordInput = screen.getByLabelText(/Password/i);
const loginButton = screen.getByRole('button', { name: /Login/i });
const loginButton = screen.getByRole('button', { name: /Log In/i });

// Mock the axios.post request to simulate an error response
mockAxios.onPost('http://localhost:8000/login').reply(401, { error: 'Unauthorized' });
Expand Down
20 changes: 15 additions & 5 deletions webapp/src/components/Question.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,19 +49,28 @@ const Question = (props) => {
const fetchQuestions = async () => {
try {
setRenderedImages(0)
let auxQuestions = []
let promises = []
let questions = []
for (let i = 0; i < questionsPerGame; i++) {
let question = ((await axios.get(`${apiEndpoint}/${props.type}/${props.category}/question`)).data)
auxQuestions.push(question)
let question = axios.get(`${apiEndpoint}/${props.type}/${props.category}/question`)
promises.push(question)
}
setQuestions(auxQuestions)
let responses = await Promise.all(promises)
for (let i = 0; i < questionsPerGame; i++) {
let question = responses.pop().data
questions.push(question)
}
setQuestions(questions)
setLoading(false)
} catch (error) {
console.error('Error fetching question:', error);
}
};

const answerQuestion = async (answer, question) => {
if(counter==0){
return
}
try {
setLoading(true);
setRenderedImages(0)
Expand Down Expand Up @@ -124,7 +133,8 @@ const Question = (props) => {
<h1 className="font-bold text-3xl text-gray-800 pl-8">{questions[currentQuestion].question}</h1>
<div class="relative h-5 rounded-full overflow-hidden bg-gray-300 mt-20 mx-10">
<div class="absolute top-0 bottom-0 left-0 rounded-full bg-gradient-to-r from-pink-500 to-purple-500"
style={{ width: counter + "%" }}></div>
style={{ width: counter + "%" }}
data-testid="time-bar"></div>
</div>
<div className="grid grid-cols-2 mt-10 item">
{questions[currentQuestion].images.map(image => (
Expand Down
18 changes: 17 additions & 1 deletion webapp/src/components/Question.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,22 @@ describe('Question page', () => {
expect(screen.getByText(/Which of the following/i)).toBeInTheDocument();
});

await act(async () => {
fireEvent.load(screen.getAllByRole("img")[0])
fireEvent.load(screen.getAllByRole("img")[1])
fireEvent.load(screen.getAllByRole("img")[2])
fireEvent.load(screen.getAllByRole("img")[3])
});

// Wait for the component to render
await waitFor(() => {
const time_bar = screen.getByTestId('time-bar');
expect(time_bar).toBeInTheDocument();
const widthStyle = time_bar.style.width;
const widthValue = parseFloat(widthStyle);
expect(widthValue).toBeGreaterThan(0);
});

await act(async () => {
fireEvent.click(screen.getAllByRole("img")[0]);
});
Expand All @@ -119,7 +135,7 @@ describe('Question page', () => {
mockAxios.onPost('http://localhost:8000/imgs/answer').reply(200,
{
correct: "false",
associate: "Poland"
correctImg: "https://commons.wikimedia.org/wiki/File:Flag_of_Spain.svg"
});

render(<Question type="imgs" category="flags"/>);
Expand Down