diff --git a/cypress/integration/Authentication/login.spec.ts b/cypress/integration/Authentication/login.spec.ts
index be7b7d9..7e177c8 100644
--- a/cypress/integration/Authentication/login.spec.ts
+++ b/cypress/integration/Authentication/login.spec.ts
@@ -8,7 +8,7 @@ describe('User Authentication', () => {
});
context('login with email and password', () => {
- it('given correct credentials, redirects to the home page', () => {
+ it('given correct credentials, redirects to the home page, shows user header', () => {
cy.intercept('POST', 'api/v1/oauth/token', {
statusCode: 200,
fixture: 'Authentication/valid-credentials.json',
@@ -27,9 +27,11 @@ describe('User Authentication', () => {
});
cy.findByTestId('app-main-heading').should('be.visible');
+
+ cy.findByTestId('header-avatar').should('have.attr', 'src', 'valid_avatar_url');
});
- it('given INCORRECT credentials, shows login error', () => {
+ it('given INCORRECT credentials, shows login error, does NOT show user header', () => {
cy.intercept('POST', 'api/v1/oauth/token', {
statusCode: 400,
fixture: 'Authentication/invalid-credentials.json',
@@ -52,6 +54,7 @@ describe('User Authentication', () => {
});
cy.findByTestId('app-main-heading').should('not.exist');
+ cy.findByTestId('header-avatar').should('not.exist');
});
it('given NO credentials entered, shows field validation errors', () => {
diff --git a/cypress/integration/Surveys/home.spec.ts b/cypress/integration/Surveys/home.spec.ts
new file mode 100644
index 0000000..8df6695
--- /dev/null
+++ b/cypress/integration/Surveys/home.spec.ts
@@ -0,0 +1,47 @@
+import { setItem } from '../../../src/helpers/localStorage';
+/* eslint-disable camelcase */
+const mockTokenData = {
+ access_token: 'test_access_token',
+ refresh_token: 'test_refresh_token',
+ token_type: 'Bearer',
+ expires_in: 7200,
+ created_at: 1677045997,
+};
+
+const mockUserProfileData = {
+ email: 'testemail@gmail.com',
+ name: 'TestName',
+ avatar_url: 'https://secure.gravatar.com/avatar/6733d09432e89459dba795de8312ac2d',
+};
+
+// TODO: Add test for expired token for surveys are shown on home page (a further authenticated request required)
+describe('Home', () => {
+ context('Authentication token', () => {
+ it('with user tokens, displays home page and user header', () => {
+ setItem('UserProfile', { auth: mockTokenData, user: mockUserProfileData });
+
+ cy.visit('/');
+
+ cy.location().should((location) => {
+ expect(location.pathname).to.eq('/');
+ });
+
+ cy.findByTestId('app-main-heading').should('be.visible');
+
+ cy.findByText('Home Screen').should('exist');
+ cy.findByText('Home Screen').should('be.visible');
+ });
+
+ it('WITHOUT user tokens, redirects to the login page', () => {
+ cy.visit('/');
+
+ cy.location().should((location) => {
+ expect(location.pathname).to.eq('/login');
+ });
+
+ cy.findByTestId('app-main-heading').should('not.exist');
+
+ cy.findByText('Home Screen').should('not.exist');
+ });
+ });
+});
diff --git a/package-lock.json b/package-lock.json
index 3a221b0..b121a2c 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -38,7 +38,7 @@
"danger": "10.9.0",
"danger-plugin-istanbul-coverage": "1.6.2",
"eslint": "8.11.0",
- "jest-localstorage-mock": "^2.4.26",
+ "jest-localstorage-mock": "2.4.26",
"nock": "13.3.0",
"postcss": "8.4.21",
"postcss-import": "14.1.0",
diff --git a/src/adapters/authAdapter.test.ts b/src/adapters/authAdapter.test.ts
index a676ea5..5448c81 100644
--- a/src/adapters/authAdapter.test.ts
+++ b/src/adapters/authAdapter.test.ts
@@ -81,4 +81,22 @@ describe('AuthAdapter', () => {
expect(scope.isDone()).toBe(true);
});
});
+
+ describe('logout', () => {
+ test('The logout endpoint is called', async () => {
+ const token = 'access_token';
+
+ const scope = nock(`${process.env.REACT_APP_API_ENDPOINT}`)
+ .defaultReplyHeaders({
+ 'access-control-allow-origin': '*',
+ 'access-control-allow-credentials': 'true',
+ })
+ .post('/oauth/revoke')
+ .reply(200);
+
+ expect(scope.isDone()).toBe(false);
+ expect(await AuthAdapter.logout(token));
+ expect(scope.isDone()).toBe(true);
+ });
+ });
});
diff --git a/src/adapters/authAdapter.ts b/src/adapters/authAdapter.ts
index e377e0e..4e79b0c 100644
--- a/src/adapters/authAdapter.ts
+++ b/src/adapters/authAdapter.ts
@@ -36,6 +36,17 @@ class AuthAdapter extends BaseAdapter {
return this.prototype.postRequest('oauth/token', { data: requestParams });
}
+ static logout(accessToken: string) {
+ /* eslint-disable camelcase */
+ const requestParams = {
+ ...OauthParams,
+ token: accessToken,
+ };
+ /* eslint-enable camelcase */
+
+ return this.prototype.postRequest('oauth/revoke', { data: requestParams });
+ }
+
static getUser() {
return this.prototype.getRequest('me', {});
}
diff --git a/src/components/Header/index.test.tsx b/src/components/Header/index.test.tsx
new file mode 100644
index 0000000..783c353
--- /dev/null
+++ b/src/components/Header/index.test.tsx
@@ -0,0 +1,41 @@
+/* eslint-disable camelcase */
+import { BrowserRouter } from 'react-router-dom';
+
+import { render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+import { User } from 'types/User';
+
+import Header from '.';
+
+const mockUserProfileData = {
+ email: 'testemail@gmail.com',
+ name: 'TestName',
+ avatar_url: 'https://secure.gravatar.com/avatar/6733d09432e89459dba795de8312ac2d',
+};
+
+describe('Header', () => {
+ const user: User = { name: 'Test User', email: 'testemail@email.com', avatarUrl: mockUserProfileData.avatar_url };
+
+ test('renders a header on the page with sidebar interaction', async () => {
+ render(, { wrapper: BrowserRouter });
+
+ const profileImage = screen.getByTestId('header-avatar') as HTMLImageElement;
+ expect(profileImage).toBeInTheDocument();
+ expect(profileImage.src).toContain(mockUserProfileData.avatar_url);
+
+ expect(screen.queryByTestId('sidebar-avatar')).not.toBeInTheDocument();
+ expect(screen.queryByTestId('username')).not.toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Logout' })).not.toBeInTheDocument();
+
+ const sidebarButton = screen.getByTestId('open-sidebar');
+
+ await userEvent.click(sidebarButton);
+
+ expect(screen.getByTestId('sidebar-avatar')).toBeInTheDocument();
+ expect(screen.getByTestId('username')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Logout' })).toBeInTheDocument();
+
+ expect(screen.queryByTestId('header-avatar')).not.toBeInTheDocument();
+ });
+});
diff --git a/src/components/Header/index.tsx b/src/components/Header/index.tsx
new file mode 100644
index 0000000..70a1176
--- /dev/null
+++ b/src/components/Header/index.tsx
@@ -0,0 +1,39 @@
+import { useState } from 'react';
+
+import logo from 'assets/images/logo.svg';
+import Sidebar from 'components/Sidebar';
+import { User } from 'types/User';
+
+type HeaderProps = {
+ user: User;
+};
+
+function Header({ user }: HeaderProps) {
+ const [sidebarVisible, setSidebarVisible] = useState(false);
+
+ return (
+
+ );
+}
+
+export default Header;
diff --git a/src/components/PrivateRoute/index.test.tsx b/src/components/PrivateRoute/index.test.tsx
index f01da45..0b6e97a 100644
--- a/src/components/PrivateRoute/index.test.tsx
+++ b/src/components/PrivateRoute/index.test.tsx
@@ -1,7 +1,7 @@
/* eslint-disable camelcase */
import { MemoryRouter } from 'react-router-dom';
-import { render, screen, waitForElementToBeRemoved } from '@testing-library/react';
+import { render, screen } from '@testing-library/react';
import PrivateRoute from '.';
import { setItem, clearItem } from '../../helpers/localStorage';
@@ -31,14 +31,17 @@ describe('PrivateRoute', () => {
render(, { wrapper: MemoryRouter });
expect(localStorage.getItem).toBeCalledWith('UserProfile');
+
+ // Only the header is rendered and not the outlet (home page)
+ // expect(screen.getByTestId('app-main-heading')).toBeVisible();
});
test.skip('renders a PrivateRoute', async () => {
// Infinite loop
render(, { wrapper: MemoryRouter });
- await waitForElementToBeRemoved(() => screen.queryAllByTestId('loading'));
+ expect(screen.getByTestId('loading')).toHaveTextContent('Loading');
- expect(screen.getByTestId('loading'));
+ // expect(screen.getByTestId('loading')).not.toBeVisible();
});
});
diff --git a/src/components/PrivateRoute/index.tsx b/src/components/PrivateRoute/index.tsx
index 52c7c33..23e6ec3 100644
--- a/src/components/PrivateRoute/index.tsx
+++ b/src/components/PrivateRoute/index.tsx
@@ -1,11 +1,10 @@
import { useState, useEffect } from 'react';
-import { Navigate, Outlet, useOutletContext } from 'react-router-dom';
+import { Navigate, Outlet } from 'react-router-dom';
+import Header from 'components/Header';
import { getItem } from 'helpers/localStorage';
import type { User } from 'types/User';
-type ContextType = User;
-
import { LOGIN_URL } from '../../constants';
function PrivateRoute() {
@@ -16,7 +15,7 @@ function PrivateRoute() {
const fetchCurrentUser = async () => {
const userProfile = getItem('UserProfile');
if (userProfile?.user) {
- setUser({ ...userProfile.user });
+ setUser({ name: userProfile.user.name, email: userProfile.user.email, avatarUrl: userProfile.user.avatar_url });
}
setLoading(false);
@@ -25,14 +24,17 @@ function PrivateRoute() {
}, []);
if (loading) {
- return
Loading...
;
+ return Loading...
;
}
- return user ? : ;
+ return user ? (
+ <>
+
+
+ >
+ ) : (
+
+ );
}
export default PrivateRoute;
-
-export function useUser() {
- return useOutletContext();
-}
diff --git a/src/components/Sidebar/Sidebar.module.scss b/src/components/Sidebar/Sidebar.module.scss
new file mode 100644
index 0000000..99fcc90
--- /dev/null
+++ b/src/components/Sidebar/Sidebar.module.scss
@@ -0,0 +1,5 @@
+.sidebar {
+ border: 5px bla solid;
+
+ background: rgba(30, 30, 30, 0.9);
+}
diff --git a/src/components/Sidebar/index.test.tsx b/src/components/Sidebar/index.test.tsx
new file mode 100644
index 0000000..0e258f9
--- /dev/null
+++ b/src/components/Sidebar/index.test.tsx
@@ -0,0 +1,65 @@
+/* eslint-disable camelcase */
+import { BrowserRouter } from 'react-router-dom';
+
+import { render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+import AuthAdapter from 'adapters/authAdapter';
+import { User } from 'types/User';
+
+import Sidebar from '.';
+import * as myStorage from '../../helpers/localStorage';
+
+const mockUserProfileData = {
+ email: 'testemail@gmail.com',
+ name: 'TestName',
+ avatar_url: 'https://secure.gravatar.com/avatar/6733d09432e89459dba795de8312ac2d',
+};
+
+const mockTokenData = {
+ access_token: 'test_access_token',
+ refresh_token: 'test_refresh_token',
+ token_type: 'Bearer',
+ expires_in: 7200,
+ created_at: 1677045997,
+};
+
+describe('Sidebar', () => {
+ const user: User = { name: 'Test User', email: 'testemail@email.com', avatarUrl: mockUserProfileData.avatar_url };
+
+ test("renders a sidebar on the page with the user's name and avatar image", () => {
+ render(, { wrapper: BrowserRouter });
+
+ expect(screen.getByTestId('username')).toHaveTextContent(user.name);
+
+ const profileImage = screen.getByTestId('sidebar-avatar') as HTMLImageElement;
+ expect(profileImage.src).toContain(mockUserProfileData.avatar_url);
+ });
+
+ test('renders a sidebar on the page with a logout button that when clicked, calls Logout adapter and removes storage', async () => {
+ const mockLogout = jest.spyOn(AuthAdapter, 'logout');
+
+ // const mockClearToken = jest.spyOn(myStorage, 'clearItem');
+
+ const storageMock = jest.spyOn(myStorage, 'getItem').mockImplementationOnce(() => {
+ return { auth: mockTokenData, user: mockUserProfileData };
+ });
+
+ expect(myStorage.getItem('UserProfile')).not.toBeNull();
+
+ render(, { wrapper: BrowserRouter });
+
+ const submitButton = screen.getByRole('button', { name: 'Logout' });
+
+ await userEvent.click(submitButton);
+
+ expect(mockLogout).toBeCalledTimes(1);
+
+ expect(myStorage.getItem('UserProfile')).toBeNull();
+
+ // navigates to LOGIN URL
+ // useNavigate is not called because redirect is handled in axios interceptor? Mock window.location.href instead?
+
+ storageMock.mockRestore();
+ });
+});
diff --git a/src/components/Sidebar/index.tsx b/src/components/Sidebar/index.tsx
new file mode 100644
index 0000000..22bfa81
--- /dev/null
+++ b/src/components/Sidebar/index.tsx
@@ -0,0 +1,51 @@
+import { useNavigate } from 'react-router-dom';
+
+import AuthAdapter from 'adapters/authAdapter';
+import { getItem, clearItem } from 'helpers/localStorage';
+import { User } from 'types/User';
+
+import styles from './Sidebar.module.scss';
+import { LOGIN_URL } from '../../constants';
+
+type SidebarProps = {
+ user: User;
+};
+
+function Sidebar({ user }: SidebarProps) {
+ const navigate = useNavigate();
+
+ const performLogout = async (e: React.SyntheticEvent) => {
+ e.stopPropagation();
+
+ const accessToken = getItem('UserProfile')?.auth.access_token;
+ await AuthAdapter.logout(accessToken);
+ clearItem('UserProfile');
+ navigate(LOGIN_URL);
+ };
+
+ return (
+
+ );
+}
+
+export default Sidebar;
diff --git a/src/screens/Home/index.tsx b/src/screens/Home/index.tsx
index f15062e..c87cb3e 100644
--- a/src/screens/Home/index.tsx
+++ b/src/screens/Home/index.tsx
@@ -1,15 +1,9 @@
-import { useUser } from 'components/PrivateRoute';
-
const HomeScreen = (): JSX.Element => {
- const user = useUser();
-
return (
<>
Home Screen
- {/* TODO: Remove when header implemented in #19 */}
- {`${user?.name} - ${user?.email} - ${user?.avatarUrl}`}
>
);
};