diff --git a/src/tests/Login.test.jsx b/src/tests/Login.test.jsx index 64646480..5c48522c 100644 --- a/src/tests/Login.test.jsx +++ b/src/tests/Login.test.jsx @@ -6,6 +6,9 @@ import '@testing-library/jest-dom'; import Login from "../login/Login"; import { act } from 'react-dom/test-utils'; import { BASE_API } from "../config"; +import { createBrowserHistory } from 'history'; +import { AuthContext } from '../AuthContext'; +import { BrowserRouter as Router, Router as Redirect } from 'react-router-dom'; const server = setupServer( rest.post(`${BASE_API}/login`, (req, res, ctx) => { @@ -27,7 +30,7 @@ afterAll(() => server.close()) it('allows the user to login successfully', async () => { - render() + render() fireEvent.change(screen.getByPlaceholderText('Username or Email'), { target: { value: 'MyUsername' }, @@ -57,7 +60,7 @@ it('handles wrong credentials', async () => { }), ) - render() + render() fireEvent.change(screen.getByPlaceholderText('Username or Email'), { target: { value: 'MyUsername' }, @@ -88,7 +91,7 @@ it('handles wrong credentials', async () => { }), ) - render() + render() fireEvent.change(screen.getByPlaceholderText('Username or Email'), { target: { value: 'MyUsername' }, @@ -109,7 +112,7 @@ it('handles wrong credentials', async () => { it('checks if the fields are empty', async () => { - render() + render() fireEvent.change(screen.getByLabelText("Username or Email:", {selector: "input"}), {target: { value: "" }}) @@ -128,7 +131,7 @@ it('checks if the fields are empty', async () => { it('handles password toggle', () => { - render() + render() expect(screen.getByPlaceholderText('Password').type).toEqual("password") @@ -138,3 +141,25 @@ it('handles password toggle', () => { expect(screen.getByPlaceholderText('Password').type).toEqual("text") }) + +it('redirects to Home if user is logged in', () => { + + const history = createBrowserHistory(); + history.replace = jest.fn(); + + const pathToHome = '/'; + + render( + + + + + + ); + + expect(screen.queryByRole('button', { name: "Login" })).not.toBeInTheDocument(); + + expect(history.replace).toHaveBeenCalledWith(expect.objectContaining({ + pathname: pathToHome, + })); +}); \ No newline at end of file diff --git a/src/tests/Navigation.test.jsx b/src/tests/Navigation.test.jsx new file mode 100644 index 00000000..46a1c58c --- /dev/null +++ b/src/tests/Navigation.test.jsx @@ -0,0 +1,23 @@ +import React from 'react'; +import { BrowserRouter } from 'react-router-dom'; +import { render } from '@testing-library/react'; +import { AuthContext } from '../AuthContext'; +import Navigation from '../Navigation'; + +const mockAuthContext = { isAuth: true, user: "AnitaB" }; + +describe('Navigation', () => { + + it('should display username when user is logged in', () => { + + const { getByText } = render( + + + + + + ); + + expect(getByText(`Welcome back, ${mockAuthContext.user}!`)).toBeInTheDocument(); + }); +});