Skip to content

Commit

Permalink
front end coverage tests
Browse files Browse the repository at this point in the history
  • Loading branch information
andrrsin committed Apr 7, 2024
1 parent 0f168c8 commit 048acf3
Show file tree
Hide file tree
Showing 7 changed files with 181 additions and 31 deletions.
25 changes: 22 additions & 3 deletions webapp/src/App.test.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,27 @@
import { render, screen } from '@testing-library/react';
import App from './App';
import AuthProvider from 'react-auth-kit/AuthProvider';
import createStore from 'react-auth-kit/createStore';

test('renders learn react link', () => {
render(<App />);
const linkElement = screen.getByText(/Welcome to the 2024 edition of the Software Architecture course/i);

test('renders /', () => {
const store = createStore({
authName: '_auth',
authType: 'cookie',
cookieDomain: window.location.hostname,
cookieSecure: window.location.protocol === 'https:',
});

render(
<AuthProvider
store={store}
>

<App />

</AuthProvider>);
const linkElement = screen.getByText(/Welcome to WIQ, Please log in to play!/i);
expect(linkElement).toBeInTheDocument();
const button = screen.getByRole('button', { name: /Create account/i });
expect(button).toBeInTheDocument();
});
7 changes: 6 additions & 1 deletion webapp/src/components/AddUser.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,12 @@ const AddUser = () => {
setOpenSnackbar(true);
navigate('/login');
} catch (error) {
setError(error.response.data.error);
if(error.response===undefined){
setError("Error: There was a problem...");
}
else{
setError(error.response.data.error);
}
}
};

Expand Down
69 changes: 61 additions & 8 deletions webapp/src/components/AddUser.test.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,54 @@
import React from 'react';
import { render, fireEvent, screen, waitFor } from '@testing-library/react';
import { fireEvent, screen, waitFor } from '@testing-library/react';
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import AddUser from './AddUser';
import { render } from '@testing-library/react';
import { BrowserRouter } from 'react-router-dom';




const mockAxios = new MockAdapter(axios);


describe('AddUser component', () => {
beforeEach(() => {
mockAxios.reset();
});

it('renders correctly', () => {
render(
<BrowserRouter>
<AddUser />
</BrowserRouter>);

expect(screen.getByLabelText('Username')).toBeInTheDocument();
expect(screen.getByLabelText('Email')).toBeInTheDocument();
expect(screen.getByLabelText('Password')).toBeInTheDocument();
expect(screen.getByLabelText('Confirm Password')).toBeInTheDocument();
});

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


const usernameInput = screen.getByLabelText(/Username/i);
const passwordInput = screen.getByLabelText(/Password/i);
const addUserButton = screen.getByRole('button', { name: /Add User/i });
const emailInput = screen.getByLabelText(/Email/i);
const passwordInput = screen.getByLabelText("Password");
const cpasswordInput = screen.getByLabelText(/Confirm Password/i);
const addUserButton = screen.getByRole('button', { name: /Register/i });

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

// Simulate user input
fireEvent.change(usernameInput, { target: { value: 'testUser' } });
fireEvent.change(passwordInput, { target: { value: 'testPassword' } });
fireEvent.change(cpasswordInput, { target: { value: 'testPassword' } });
fireEvent.change(emailInput, { target: { value: '[email protected]' } });

// Trigger the add user button click
fireEvent.click(addUserButton);
Expand All @@ -34,12 +59,40 @@ describe('AddUser component', () => {
});
});

it('should handle wrong passwords when adding user', async () => {
render(<BrowserRouter>
<AddUser />
</BrowserRouter>);

const usernameInput = screen.getByLabelText(/Username/i);
const passwordInput = screen.getByLabelText("Password");
const addUserButton = screen.getByRole('button', { name: /Register/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(passwordInput, { 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: Passwords do not match")).toBeInTheDocument();
});
});

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

const usernameInput = screen.getByLabelText(/Username/i);
const passwordInput = screen.getByLabelText(/Password/i);
const addUserButton = screen.getByRole('button', { name: /Add User/i });
const passwordInput = screen.getByLabelText("Password");
const addUserButton = screen.getByRole('button', { name: /Register/i });

// Mock the axios.post request to simulate an error response
mockAxios.onPost('http://localhost:8000/adduser').reply(500, { error: 'Internal Server Error' });
Expand All @@ -53,7 +106,7 @@ describe('AddUser component', () => {

// Wait for the error Snackbar to be open
await waitFor(() => {
expect(screen.getByText(/Error: Internal Server Error/i)).toBeInTheDocument();
expect(screen.getByText("Error: Passwords do not match")).toBeInTheDocument();
});
});
});
11 changes: 10 additions & 1 deletion webapp/src/components/Login.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ const Login = () => {
const loginUser = async () => {
try {
const response = await axios.post(`${apiEndpoint}/login`, { username, password }).then((res) => {

if (res.status === 200) {
if (signIn({
auth: {
Expand All @@ -35,14 +36,22 @@ const Login = () => {
navigate('/');
} else {
//Throw error

throw new Error('Error while signing in');
}

}
});

setOpenSnackbar(true);
} catch (error) {
setError(error.response.data.error);
if(error.response===undefined){
setError("Error: There was a problem...");
}
else{
setError(error.response.data.error);
}

}
};

Expand Down
66 changes: 50 additions & 16 deletions webapp/src/components/Login.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ 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 'react-auth-kit/AuthProvider';
import { BrowserRouter } from 'react-router-dom';
import createStore from 'react-auth-kit/createStore';
const mockAxios = new MockAdapter(axios);

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

it('should log in successfully', async () => {
render(<Login />);
const store = createStore({
authName: '_auth',
authType: 'cookie',
cookieDomain: window.location.hostname,
cookieSecure: window.location.protocol === 'https:',
});

render(
<AuthProvider
store={store}
>
<BrowserRouter>
<Login/>
</BrowserRouter>
</AuthProvider>);

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

const mock = jest.fn();
jest.mock('react-router-dom', () => ({
useNavigate: () => mock,
}));
// 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, { username:"testUser",email:"[email protected]",createdAt: '2024-01-01T12:34:56Z',token: 'testToken'});

// Simulate user input
await act(async () => {
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(/Hello testUser!/i)).toBeInTheDocument();
expect(screen.getByText(/Your account was created on 1\/1\/2024/i)).toBeInTheDocument();
fireEvent.change(usernameInput, { target: { value: 'testUser' } });
fireEvent.change(passwordInput, { target: { value: 'testPassword' } });
fireEvent.click(loginButton);
});


const linkElement = screen.getByText(/Error: Error: There was a problem.../i);
expect(linkElement).toBeInTheDocument();


});

it('should handle error when logging in', async () => {
render(<Login />);
const store = createStore({
authName: '_auth',
authType: 'cookie',
cookieDomain: window.location.hostname,
cookieSecure: window.location.protocol === 'https:',
});

render(
<AuthProvider
store={store}
>
<BrowserRouter>
<Login/>
</BrowserRouter>
</AuthProvider>);

const usernameInput = screen.getByLabelText(/Username/i);
const passwordInput = screen.getByLabelText(/Password/i);
Expand All @@ -55,8 +90,7 @@ describe('Login component', () => {
expect(screen.getByText(/Error: Unauthorized/i)).toBeInTheDocument();
});

// Verify that the user information is not displayed
expect(screen.queryByText(/Hello testUser!/i)).toBeNull();
expect(screen.queryByText(/Your account was created on/i)).toBeNull();
});


});
4 changes: 2 additions & 2 deletions webapp/src/components/MainPage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,13 @@ const MainPage = () => {
<div>
<h1 className="text-6xl font-bold text-zinc-700">Welcome back, {auth.username}!</h1>
<hr className=" my-8"/>
<button class="px-8 py-4 bg-gradient-to-r from-blue-500 to-purple-500 text-white font-bold rounded-full transition-transform transform-gpu hover:-translate-y-1 hover:shadow-lg" onClick={() => navigate("/play")}>
<button className="px-8 py-4 bg-gradient-to-r from-blue-500 to-purple-500 text-white font-bold rounded-full transition-transform transform-gpu hover:-translate-y-1 hover:shadow-lg" onClick={() => navigate("/play")}>
Start Playing
</button>
</div>:
<div>
<h1 className="text-6xl font-bold text-zinc-700">Welcome to WIQ, Please log in to play!</h1>
<button class="px-8 py-4 bg-gradient-to-r from-blue-500 to-purple-500 text-white font-bold rounded-full transition-transform transform-gpu hover:-translate-y-1 hover:shadow-lg" onClick={() => navigate("/register")}>
<button className="px-8 py-4 bg-gradient-to-r from-blue-500 to-purple-500 text-white font-bold rounded-full transition-transform transform-gpu hover:-translate-y-1 hover:shadow-lg" onClick={() => navigate("/register")}>
Create account
</button>
</div>
Expand Down
30 changes: 30 additions & 0 deletions webapp/src/components/MainPage.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import { jest } from '@jest/globals';
import MainPage from './MainPage';
import useIsAuthenticated from 'react-auth-kit/hooks/useIsAuthenticated';
import useAuthUser from 'react-auth-kit/hooks/useAuthUser';


jest.mock('react-auth-kit/hooks/useIsAuthenticated');
jest.mock('react-auth-kit/hooks/useAuthUser');
const mock = jest.fn();
jest.mock('react-router-dom', () => ({
useNavigate: () => mock,
}));
describe('MainPage', () => {
it('renders welcome message for authenticated user', () => {
useIsAuthenticated.mockReturnValue(() => true);
useAuthUser.mockReturnValue({ username: 'testUser' });
const { getByText } = render(<MainPage />);
expect(getByText('Welcome back, testUser!')).toBeInTheDocument();
});

it('renders welcome message for unauthenticated user', () => {
useIsAuthenticated.mockReturnValue(() => false);
const { getByText } = render(<MainPage />);
expect(getByText('Welcome to WIQ, Please log in to play!')).toBeInTheDocument();
});


});

0 comments on commit 048acf3

Please sign in to comment.