Skip to content

Commit

Permalink
Merge branch 'develop' into user_profile
Browse files Browse the repository at this point in the history
  • Loading branch information
uo287841 committed Apr 24, 2024
2 parents c972a55 + 21260f7 commit e917ff2
Show file tree
Hide file tree
Showing 5 changed files with 59 additions and 35 deletions.
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
27 changes: 4 additions & 23 deletions webapp/src/components/Login.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ const Login = () => {

<Container component="main" maxWidth="xs" sx={{ marginTop: 4 }}>
<Typography component="h1" variant="h5">
Register
Log in to WIQ
</Typography>
<TextField
name="username"
Expand All @@ -75,15 +75,6 @@ const Login = () => {
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
<TextField
name="email"
type='email'
margin="normal"
fullWidth
label="Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<TextField
name="password"
margin="normal"
Expand All @@ -93,21 +84,11 @@ const Login = () => {
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<TextField
name="cpassword"

margin="normal"
fullWidth
label="Confirm Password"
type="password"
value={cpassword}
onChange={(e) => setcPassword(e.target.value)}
/>
<Button variant="contained" color="primary" onClick={addUser}>
Register
<Button variant="contained" color="primary" onClick={loginUser}>
Log In
</Button>
<Typography component="div" align="center" sx={{ marginTop: 2 }}>
<Link to="/login">Already have an account? Log in here.</Link>
<Link to="/register">New around here? Create account.</Link>
</Typography>


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

0 comments on commit e917ff2

Please sign in to comment.