Skip to content

Commit

Permalink
Add unit test
Browse files Browse the repository at this point in the history
  • Loading branch information
nathanfranklin committed Dec 4, 2024
1 parent 45ff038 commit 10dad3f
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
73 changes: 73 additions & 0 deletions react/src/components/HeaderNavBar/HeaderNavBar.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import React from 'react';
import { fireEvent } from '@testing-library/react';
import * as ROUTES from '@hazmapper/constants/routes';
import { renderInTest } from '@hazmapper/test/testUtil';
import { HeaderNavBar } from './HeaderNavBar';

const mockNavigate = jest.fn();

jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useNavigate: () => mockNavigate,
useLocation: () => ({
pathname: '/project-public/cd010f4d-3975-4fde-8bbd-b81ffb87273f',
}),
}));

const mockAuthenticatedUser = {
data: null,
isLoading: false,
error: null,
};

jest.mock('@hazmapper/hooks/user/useAuthenticatedUser', () => {
return {
__esModule: true,
default: () => {
return { ...mockAuthenticatedUser };
},
};
});

describe('HeaderNavBar', () => {
beforeEach(() => {
mockNavigate.mockClear();
mockAuthenticatedUser.data = null;
});

test('clicking login button should navigate to login with correct return URL', () => {
const { getByText } = renderInTest(<HeaderNavBar />);

const loginButton = getByText('Login');
fireEvent.click(loginButton);

const expectedPath = '/project-public/cd010f4d-3975-4fde-8bbd-b81ffb87273f';
const expectedUrl = `${ROUTES.LOGIN}?to=${encodeURIComponent(
expectedPath
)}`;

expect(mockNavigate).toHaveBeenCalledTimes(1);
expect(mockNavigate).toHaveBeenCalledWith(expectedUrl);
expect(mockNavigate).not.toHaveBeenCalledWith(ROUTES.MAIN);
});

test('clicking header should navigate to main', () => {
const { getByRole } = renderInTest(<HeaderNavBar />);

const header = getByRole('button', { name: 'return to project listings' });
fireEvent.click(header);

expect(mockNavigate).toHaveBeenCalledWith(ROUTES.MAIN);
});

test('displays username when user is authenticated', () => {
Object.assign(mockAuthenticatedUser, {
data: { username: 'testUser' },
});

const { getByText, queryByText } = renderInTest(<HeaderNavBar />);

expect(getByText('testUser')).toBeDefined();
expect(queryByText('Login')).toBeNull();
});
});
1 change: 1 addition & 0 deletions react/src/components/HeaderNavBar/HeaderNavBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export const HeaderNavBar: React.FC = () => {
onKeyDown={() => navigate(ROUTES.MAIN)}
onClick={() => navigate(ROUTES.MAIN)}
role="button"
aria-label="return to project listings"
tabIndex={0}
>
<img
Expand Down

0 comments on commit 10dad3f

Please sign in to comment.