Skip to content

Commit

Permalink
Extension of tests
Browse files Browse the repository at this point in the history
Tests extended
  • Loading branch information
andrrsin authored Apr 26, 2024
2 parents 091722d + 6908f74 commit 35d726c
Show file tree
Hide file tree
Showing 4 changed files with 162 additions and 20 deletions.
43 changes: 41 additions & 2 deletions gatewayservice/gateway-service.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ describe('Gateway Service', () => {
}
});

axios.get.mockImplementation((url) => {
axios.get.mockImplementation((url,data) => {
if (url.endsWith('/imgs/flags/question')) {
return generateMockResponse(url, [
{ item: 'Flag0', itemLabel: 'Country0', image: 'flag0.jpg' },
Expand Down Expand Up @@ -87,8 +87,16 @@ describe('Gateway Service', () => {
]);
} else if (url.endsWith('/rankings/category1')) {
return Promise.resolve({ data: mockUserData });
} else if (url.endsWith('/ranking/user')) {
return Promise.resolve({data:{
username: data.params.username,
category: data.params.category,
points: 5,
questions: 7,
correct: 5,
wrong: 2
}});
}

});

// Test /login endpoint
Expand Down Expand Up @@ -263,6 +271,37 @@ it('should forward get Foods request to question service', async () => {

});

// Test /health endpoint
it('should inform that the health is OK if the service is operative', async () => {

// Send POST request to gateway endpoint
const response = await request(app)
.get('/health')

// Verify response body
expect(response.body.status).toEqual('OK');
});

// Test /ranking/user
it('should respond with the ranking info of the given user', async () => {

// Send POST request to gateway endpoint
const response = await request(app)
.get('/ranking/user')
.query({
username: "username",
category: "category"
})

// Verify response body
expect(response.body).toEqual({
username: "username",
category: "category",
points: 5,
questions: 7,
correct: 5,
wrong: 2
});
});

});
12 changes: 11 additions & 1 deletion webapp/src/components/AddUser.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React from 'react';
import { fireEvent, screen, waitFor } from '@testing-library/react';
import { fireEvent, act, screen, waitFor } from '@testing-library/react';
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import AddUser from './AddUser';
Expand Down Expand Up @@ -108,5 +108,15 @@ describe('AddUser component', () => {
await waitFor(() => {
expect(screen.getByText("Error: Passwords do not match")).toBeInTheDocument();
});

//Close the snackbar by clicking outside
await act(async ()=>{
fireEvent.click(screen.getAllByText("Username")[1])
})

//Snackbar has to have been closed
await waitFor(() => {
expect(screen.queryByText("Error: Passwords do not match")).not.toBeInTheDocument();
});
});
});
45 changes: 43 additions & 2 deletions webapp/src/components/Game.test.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import { fireEvent, act, render, screen, waitFor } from '@testing-library/react';
import Game from './Game';
import { jest } from '@jest/globals';
import useIsAuthenticated from 'react-auth-kit/hooks/useIsAuthenticated';
import useAuthUser from 'react-auth-kit/hooks/useAuthUser';
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
const mockAxios = new MockAdapter(axios);

const mock = jest.fn();

Expand All @@ -13,6 +16,14 @@ jest.mock('react-router-dom', () => ({
useNavigate: () => mock,
}));

mockAxios.onGet(/\/imgs\/([^\/]+)\/question/).reply(config => {
const category = config.url.match(/\/imgs\/([^\/]+)\/question/)[1];
return [200, {
question: `${category} question`,
images: ["img1", "img2", "img3", "img4"]
}];
});

describe('Game page', () => {
it('should render play message for authenticated user', async () => {
useIsAuthenticated.mockReturnValue(() => true);
Expand All @@ -31,5 +42,35 @@ describe('Game page', () => {
throw new Error('Unauthenticated user was able to see Game page');
} catch (err) {}
});


it('should render the corresponding question depending on the option clicked', async () => {
useIsAuthenticated.mockReturnValue(() => true);
useAuthUser.mockReturnValue({ username: 'testUser' });

let gameOptions = ["Flag","City","Monument","Tourist attraction","Food"]
let gameCategories = ["flags","cities","monuments","tourist_attractions","foods"]

for(let i=0;i<gameOptions.length;i++){
render(<Game />);
//Click game option
await act(async ()=>{
fireEvent.click(screen.getByText(gameOptions[i]))
})

//Should have rendered question category
await waitFor(()=>{
expect(screen.getByText(gameCategories[i]+" question")).toBeInTheDocument()
})
}
});

it('should navigate out of the game if the user is not authenticated', async () => {
useIsAuthenticated.mockReturnValue(() => false);
useAuthUser.mockReturnValue({ username: 'testUser' });

render(<Game />);
await waitFor(()=>{
expect(screen.queryByText("Let's Play!")).not.toBeInTheDocument();
})
});
});
82 changes: 67 additions & 15 deletions webapp/src/components/Question.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,25 @@ jest.mock('react-router-dom', () => ({
useNavigate: () => mock,
}));

async function loadImages(){
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])
});
}

async function waitForTimeBarStart(){
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);
});
}

describe('Question page', () => {
beforeEach(() => {
mockAxios.reset();
Expand Down Expand Up @@ -95,21 +114,8 @@ 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 loadImages()
await waitForTimeBarStart()

await act(async () => {
fireEvent.click(screen.getAllByRole("img")[0]);
Expand Down Expand Up @@ -153,6 +159,52 @@ describe('Question page', () => {
expect(screen.getByText(/Score/i).textContent).toBe("Score: 0")
})
});

it('should finish the game and render the report, from which game can be restarted', async () => {
useAuthUser.mockReturnValue({ username: 'testUser' });

mockAxios.onGet('http://localhost:8000/imgs/flags/question').reply(200,
{
question: "Which of the following flags belongs to Spain?",
images:["https://commons.wikimedia.org/wiki/File:Flag_of_Spain.svg"
,"https://commons.wikimedia.org/wiki/File:Flag_of_England.svg"
,"https://commons.wikimedia.org/wiki/File:Flag_of_Poland.svg"
,"https://commons.wikimedia.org/wiki/File:Flag_of_Germany.svg"]
});

mockAxios.onPost('http://localhost:8000/imgs/answer').reply(200,
{
correct: "false",
correctImg: "https://commons.wikimedia.org/wiki/File:Flag_of_Spain.svg"
});

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

await waitFor(() => {
expect(screen.getByText(/Which of the following/i)).toBeInTheDocument();
});

const questionsPerGame = 10;
for(let i=0;i<questionsPerGame;i++){
await loadImages()
await waitForTimeBarStart()
await act(async () => {
fireEvent.click(screen.getAllByRole("img")[2]);
});
}

await waitFor(() => {
expect(screen.queryByText("Game Over!")).toBeInTheDocument()
})

await act(async ()=>{
fireEvent.click(screen.getByText("Restart Game"))
})

await waitFor(() => {
expect(screen.queryByText(/Which of the following/i)).toBeInTheDocument()
})
});
});


Expand Down

0 comments on commit 35d726c

Please sign in to comment.