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

Uo277382 #113

Merged
merged 9 commits into from
Apr 6, 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
7 changes: 4 additions & 3 deletions webapp/src/components/Inicio.test.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
import { render, screen, fireEvent } from '@testing-library/react';
import Inicio from './Inicio';
import AuthProvider from './login/AuthProvider';

test('renders learn react link', () => {
render(<Inicio />);
render(<AuthProvider><Inicio /></AuthProvider>);
const linkElement = screen.getByText(/Welcome to WIQ/i);
expect(linkElement).toBeInTheDocument();
});

test('test mostrar login', () => {
render(<Inicio />);
render(<AuthProvider><Inicio /></AuthProvider>);
const linkElement = screen.getByRole('button', {
name: /login/i
})
expect(linkElement).toBeInTheDocument();
});

test('test crear cuenta', () => {
render(<Inicio />);
render(<AuthProvider><Inicio /></AuthProvider>);
fireEvent.click(screen.getByRole('button', {
name: "Don't have an account? Register here."
}));
Expand Down
3 changes: 2 additions & 1 deletion webapp/src/components/Navbar.test.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { render, screen } from '@testing-library/react';
import { BrowserRouter as Router } from "react-router-dom";
import Navbar from './Navbar';
import AuthProvider from './login/AuthProvider';

test('renders navbar', () => {
render(<Router> <Navbar /></Router>);
render(<AuthProvider><Router> <Navbar /></Router></AuthProvider>);
const linkElement = screen.getByText("Home");
expect(linkElement).toBeInTheDocument();

Expand Down
2 changes: 0 additions & 2 deletions webapp/src/components/Primera.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@ import "./Primera.css";

function Primera() {



return (
<div className="box">
<Container>
Expand Down
3 changes: 2 additions & 1 deletion webapp/src/components/QuizGame.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { render, screen, fireEvent } from '@testing-library/react';
import QuizGame from './QuizGame';
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import AuthProvider from './login/AuthProvider';

const mockAxios = new MockAdapter(axios);

Expand All @@ -16,7 +17,7 @@ beforeEach(() => {
allAnswers: ["correcta", "no1", "no2", "no3"]
});

render(<QuizGame />);
render(<AuthProvider><QuizGame /></AuthProvider>);
expect(screen.getByText(/Loading questions.../i)).toBeInTheDocument();

// Wait for the asynchronous operation to complete
Expand Down
24 changes: 10 additions & 14 deletions webapp/src/components/login/Login.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// src/components/Login.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Container, Typography, TextField, Button, Snackbar } from '@mui/material';
import './Login.css';
import { useAuth } from "./AuthProvider";
import axios from 'axios';


const Login = () => {
Expand All @@ -22,13 +22,7 @@ const Login = () => {
const loginUser = async () => {
try {

if (username.trim().length === 0 || password.trim().length === 0) {
setError("No se permite dejar espacios en blanco");
return;
}

let res = await axios.post(`${apiEndpoint}/login`, { username, password });

let res= await axios.post(`${apiEndpoint}/login`, { username, password });

// Extract data from the response
setToken(res.data.token);
Expand All @@ -48,6 +42,8 @@ const Login = () => {
setError("No se permite dejar espacios en blanco");
return;
}

loginUser();
};

const handleCloseSnackbar = () => {
Expand Down Expand Up @@ -83,7 +79,7 @@ const Login = () => {
fullWidth
label="Username"
name='username'
id="input"
id="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
Expand All @@ -97,12 +93,12 @@ const Login = () => {
name = "password"
value={password}
onChange={(e) => setPassword(e.target.value)}
id="input"
id="password"
/>
</div>
<div className="underline"></div>
<div className='button'>
<Button variant="contained" color="primary" onClick={loginUser}>
</div>
<div className="underline"></div>
<div className='button'>
<Button variant="contained" color="primary" onClick={checkForm}>
Login
</Button>
</div>
Expand Down
29 changes: 16 additions & 13 deletions webapp/src/components/login/Login.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { render, fireEvent, screen, waitFor, act } from '@testing-library/react'
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import Login from './Login';
import AuthProvider from './AuthProvider';

const mockAxios = new MockAdapter(axios);

Expand All @@ -12,29 +13,31 @@ describe('Login component', () => {
});

it('should log in successfully', async () => {
render(<Login />);
render(<AuthProvider><Login /></AuthProvider>);

const usernameInput = screen.getByLabelText(/Username/i);
const passwordInput = screen.getByLabelText(/Password/i);
//const usernameInput = screen.getByLabelText(/Username/i);
const usernameInput = document.getElementById("username");
//const passwordInput = screen.getByLabelText(/Password/i);
const passwordInput = document.getElementById("password");
const loginButton = screen.getByRole('button', { name: /Login/i });

// Mock the axios.post request to simulate a successful response
mockAxios.onPost('http://localhost:8000/login').reply(200, { createdAt: '2024-01-01T12:34:56Z' });
mockAxios.onPost('http://localhost:8000/login').reply(200, { createdAt: '2024-01-01T12:34:56Z', token:'12345' });

// Simulate user input
await act(async () => {
fireEvent.change(usernameInput, { target: { value: 'testUser' } });
fireEvent.change(passwordInput, { target: { value: 'testPassword' } });
fireEvent.click(loginButton);
});
fireEvent.change(usernameInput, { target: { value: 'testUser' } });
fireEvent.change(passwordInput, { target: { value: 'testPassword' } });
fireEvent.click(loginButton);


// Verify that the user information is displayed
expect(screen.getByText(/Login successful/i)).toBeInTheDocument();
//expect(screen.getByText(/Your account was created on 1\/1\/2024/i)).toBeInTheDocument();
await waitFor(() => {
expect(screen.getByText(/Login successful/i)).toBeInTheDocument();
});
});

it('should handle error when logging in', async () => {
render(<Login />);
render(<AuthProvider><Login /></AuthProvider>);

const usernameInput = screen.getByLabelText(/Username/i);
const passwordInput = screen.getByLabelText(/Password/i);
Expand All @@ -52,7 +55,7 @@ describe('Login component', () => {

// Wait for the error Snackbar to be open
await waitFor(() => {
expect(screen.getByText(/Error: Unauthorized/i)).toBeInTheDocument();
expect(screen.getByText(/Error: /i)).toBeInTheDocument();
});

// Verify that the user information is not displayed
Expand Down
11 changes: 9 additions & 2 deletions webapp/src/components/register/AddUser.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,20 @@ import React, { useState } from 'react';
import axios from 'axios';
import { Container, Typography, TextField, Button, Snackbar } from '@mui/material';
import './AddUser.css';

import { useAuth } from "../login/AuthProvider";

const apiEndpoint = process.env.REACT_APP_API_ENDPOINT || 'http://localhost:8000';

const AddUser = () => {
const {setToken} = useAuth();
const [name, setName] = useState('');
const [surname, setSurName] = useState('');
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [passwordRepeat, setPasswordRepeat] = useState('');
const [error, setError] = useState('');
const [openSnackbar, setOpenSnackbar] = useState(false);
const [openSnackbar, setOpenSnackbar] = useState(false);


const addUser = async () => {
try {
Expand All @@ -26,6 +28,11 @@ const AddUser = () => {
passwordRepeat
});
setOpenSnackbar(true);

let res= await axios.post(`${apiEndpoint}/login`, { username, password });

setToken(res.data.token);

window.location.href = '/home';
} catch (error) {
setError(error.response.data.error);
Expand Down
29 changes: 21 additions & 8 deletions webapp/src/components/register/AddUser.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { render, fireEvent, screen, waitFor } from '@testing-library/react';
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import AddUser from './AddUser';
import AuthProvider from '../login/AuthProvider';

const mockAxios = new MockAdapter(axios);

Expand All @@ -12,7 +13,7 @@ describe('AddUser component', () => {
});

it('should add user successfully', async () => {
render(<AddUser />);
render(<AuthProvider><AddUser /></AuthProvider>);

/*const usernameInput = screen.getByLabelText(/Nombre de Usuario/i);
const nameInput = screen.getByLabelText(/Nombre/i);
Expand All @@ -31,6 +32,11 @@ describe('AddUser component', () => {

// Mock the axios.post request to simulate a successful response
mockAxios.onPost('http://localhost:8000/adduser').reply(200);

mockAxios.onPost('http://localhost:8000/login').reply(200,
{
token:'12345'
});

// Simulate user input
fireEvent.change(usernameInput, { target: { value: 'testUser' } });
Expand All @@ -49,25 +55,32 @@ describe('AddUser component', () => {
});

it('should handle error when adding user', async () => {
render(<AddUser />);
render(<AuthProvider><AddUser /></AuthProvider>);

const usernameInput = document.getElementById("username");
fireEvent.change(passwordInput, { target: { value: 'testPassword' } });
const nameInput = document.getElementById("name");
const surnameInput = document.getElementById("surname");
const passwordInput = document.getElementById("password");
const password2Input = document.getElementById("password2");

const addUserButton = screen.getByRole('button', { name: /Registrarse/i });

// Mock the axios.post request to simulate an error response
mockAxios.onPost('http://localhost:8000/adduser').reply(500, { error: 'Internal Server Error' });

// Simulate user input
fireEvent.change(usernameInput, { target: { value: 'testUser' } });
fireEvent.change(passwordInput, { target: { value: 'testPassword' } });
fireEvent.change(usernameInput, { target: { value: 'testUser' } });
fireEvent.change(nameInput, { target: { value: 'testUser' } });
fireEvent.change(surnameInput, { target: { value: 'testUser' } });
fireEvent.change(passwordInput, { target: { value: 'testPassword' } });
fireEvent.change(password2Input, { target: { value: 'testPassword' } });

// Trigger the add user button click
fireEvent.click(addUserButton);

// Wait for the error Snackbar to be open
await waitFor(() => {
expect(screen.getByText(/Error: No se permite dejar espacios en blanco/i)).toBeInTheDocument();
await waitFor(() => {
expect(screen.getByText(/Error: /i)).toBeInTheDocument();
});
});
});
});