Skip to content

Commit

Permalink
feat: merging master changes with stabilizaing auth0 (#130)
Browse files Browse the repository at this point in the history
## Description

<!-- Write and explain of the changes introduced by this PR for the reviewers to fully understand -->

## Screenshot

<!-- Provide a screenshot or gif of the change to demonstrate it -->

## Test Plan

<!-- Explain what you tested and why -->

<!--
  Have any questions? Check out the contributing doc for more
-->
  • Loading branch information
mkarajohn committed Mar 13, 2024
2 parents 7f87914 + a430f92 commit 402fd6f
Show file tree
Hide file tree
Showing 19 changed files with 3,542 additions and 1,190 deletions.
13 changes: 8 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@
"license": "MIT",
"dependencies": {
"@auth0/auth0-spa-js": "^2.1.2",
"axios": "^0.21.4",
"axios-mock-adapter": "^1.19.0",
"axios": "^1.6.7",
"axios-mock-adapter": "^1.22.0",
"dayjs": "^1.11.10",
"jwt-decode": "^3.1.2",
"polished": "^4.2.2",
Expand All @@ -49,7 +49,7 @@
"@testing-library/react": "^13.0.0",
"@testing-library/react-hooks": "^7.0.2",
"@testing-library/user-event": "^14.0.4",
"@types/jest": "^27.4.1",
"@types/jest": "^29.5.12",
"@types/jwt-encode": "^1.0.0",
"@types/react": "^17.0.44",
"@types/react-router-dom": "^5.1.7",
Expand All @@ -60,7 +60,9 @@
"eslint-plugin-react": "^7.31.10",
"eslint-plugin-react-hooks": "^4.6.0",
"husky": "^8.0.0",
"jest": "^27.5.1",
"identity-obj-proxy": "^3.0.0",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"jest-sonar-reporter": "^2.0.0",
"jwt-encode": "^1.0.1",
"lint-staged": "^12.4.1",
Expand All @@ -71,7 +73,8 @@
"react-router-dom": "^5.3.1",
"rimraf": "^3.0.2",
"rollup": "^4.12.0",
"ts-jest": "^27.1.4",
"semantic-release": "^22.0.12",
"ts-jest": "^29.1.2",
"ts-lib": "^0.0.5",
"tsc-watch": "^5.0.3",
"tslib": "^2.3.1",
Expand Down
78 changes: 36 additions & 42 deletions src/__tests__/Authentication.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,8 @@ class CustomError extends Error {

import { ErrorBoundary, useErrorHandler } from 'react-error-boundary';

import {
FAKE_TOKEN,
fakeTokenData,
getNewFakeToken,
getUser,
isAuthenticated,
loginWithRedirect,
getTokenSilently as mockedGetTokenSilently,
handleRedirectCallback as mockedHandleRedirectCallback,
} from '__mocks__/@auth0/auth0-spa-js';
import { Auth0Client } from '@auth0/auth0-spa-js';
import { FAKE_TOKEN, fakeTokenData, getNewFakeToken } from '__mocks__/@auth0/auth0-spa-js';
import { defaultAuthenticationContextValues } from '~/contexts/authentication';
import { useAuthentication } from '~/hooks';
import { Authentication } from '~/providers/Authentication';
Expand All @@ -32,6 +24,7 @@ import MockRequest from '~/request/mock';
import useOrganization from '~/store/organizations';
import useRequestToken from '~/store/requestToken';
import { getTokenSilently, logoutAuth, onRedirectCallback } from '~/utils/auth';
const clientMock = jest.mocked(new Auth0Client({ clientId: '', domain: '' }));

const TestingComponentSimple = () => {
const { user, isAuthenticated, isLoading } = useAuthentication();
Expand Down Expand Up @@ -59,7 +52,7 @@ const TestingComponent = () => {
if (res?.token) {
setResult(res.token);
}
} catch (err: any) {
} catch (err) {
handleError(err);
throw err;
}
Expand Down Expand Up @@ -99,7 +92,7 @@ describe('Context', () => {
login_url: 'string',
},
]);
mockedGetTokenSilently.mockReset();
clientMock.getTokenSilently.mockReset();
});

afterEach(() => {
Expand All @@ -108,9 +101,9 @@ describe('Context', () => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
mock.reset();
mockedGetTokenSilently.mockReset();
getUser.mockReset();
loginWithRedirect.mockReset();
clientMock.getTokenSilently.mockReset();
clientMock.getUser.mockReset();
clientMock.loginWithRedirect.mockReset();
});

describe('global methods that used on both context and outside', () => {
Expand All @@ -135,19 +128,23 @@ describe('Context', () => {
test('handleRedirectCallback being called if code exists on url', async () => {
window.history.pushState({}, '', '?code=test');

const mockedHandleRedirectCallback = clientMock.handleRedirectCallback;

render(
<Authentication>
<></>
</Authentication>
);

await waitFor(() => expect(mockedHandleRedirectCallback).toBeCalledTimes(1));
await waitFor(() => expect(mockedHandleRedirectCallback).toBeCalledTimes(1), {
timeout: 1000,
});
});

test('handleRedirectCallback that triggers invalid state error', async () => {
window.history.pushState({}, '', '?code=test');

// @ts-ignore
const mockedHandleRedirectCallback = clientMock.handleRedirectCallback;
mockedHandleRedirectCallback.mockRejectedValue(new Error('Invalid state'));

render(
Expand All @@ -162,14 +159,14 @@ describe('Context', () => {
);

await waitFor(() => expect(mockedHandleRedirectCallback).toBeCalledTimes(1));
await waitFor(() => expect(loginWithRedirect).toBeCalledTimes(1));
await waitFor(() => expect(clientMock.loginWithRedirect).toBeCalledTimes(1));
});

test('handleRedirectCallback that triggers error', async () => {
window.history.pushState({}, '', '?code=test');
const errorMsg = 'Invalid';

// @ts-ignore
const mockedHandleRedirectCallback = clientMock.handleRedirectCallback;
mockedHandleRedirectCallback.mockRejectedValue(new Error(errorMsg));

render(
Expand Down Expand Up @@ -226,7 +223,7 @@ describe('Context', () => {

describe('getTokenSilently', () => {
test('without cached results', async () => {
mockedGetTokenSilently.mockResolvedValue(FAKE_TOKEN);
clientMock.getTokenSilently.mockResolvedValue(FAKE_TOKEN);
const { token, decodedToken } = await getTokenSilently();

expect(token).toBe(FAKE_TOKEN);
Expand Down Expand Up @@ -269,7 +266,7 @@ describe('Context', () => {

test('that throws error and handles it outside exclusion of login_required', async () => {
const errorThrown = new CustomError('error', 'error');
mockedGetTokenSilently.mockRejectedValue(errorThrown);
clientMock.getTokenSilently.mockRejectedValue(errorThrown);

try {
await getTokenSilently();
Expand All @@ -280,10 +277,11 @@ describe('Context', () => {
});

test('Authentication contents', async () => {
mockedGetTokenSilently.mockResolvedValue(FAKE_TOKEN);
isAuthenticated.mockResolvedValue(true);
getUser.mockResolvedValue({
clientMock.getTokenSilently.mockResolvedValue(FAKE_TOKEN);
clientMock.isAuthenticated.mockResolvedValue(true);
clientMock.getUser.mockResolvedValue({
name: 'John Doe',
updated_at: new Date().toDateString(),
});

const { findByText, getByTestId } = render(
Expand All @@ -300,7 +298,7 @@ describe('Context', () => {
test('loginWithRedirect when access token fails', async () => {
const errorMsg = 'login_required';

mockedGetTokenSilently.mockRejectedValue(new CustomError(errorMsg, errorMsg));
clientMock.getTokenSilently.mockRejectedValue(new CustomError(errorMsg, errorMsg));

render(
// @ts-ignore
Expand All @@ -313,14 +311,16 @@ describe('Context', () => {
</ErrorBoundary>
);

await waitFor(() => expect(loginWithRedirect).toBeCalledTimes(1));
await waitFor(() => expect(clientMock.logout).toBeCalledTimes(1));
});

test('loginWithRedirect when access token fails and handle an error', async () => {
const errorMsg = 'login_with_popup_failed';
const errorMsg = 'login_required';

mockedGetTokenSilently.mockRejectedValue(new CustomError('login_required', 'login_required'));
loginWithRedirect.mockImplementation(() => {
clientMock.getTokenSilently.mockRejectedValue(
new CustomError('login_required', 'login_required')
);
clientMock.loginWithRedirect.mockImplementation(() => {
throw new Error(errorMsg);
});

Expand All @@ -335,7 +335,7 @@ describe('Context', () => {
</ErrorBoundary>
);

await waitFor(() => expect(loginWithRedirect).toBeCalledTimes(1));
await waitFor(() => expect(clientMock.logout).toBeCalledTimes(1));

await waitFor(() => expect(screen.getByTestId('errorboundary')).toBeVisible());
await waitFor(() => expect(screen.getByTestId('errorboundary').innerHTML).toBe(errorMsg));
Expand All @@ -353,7 +353,7 @@ describe('Context', () => {
writable: true,
});

isAuthenticated.mockResolvedValue(false);
clientMock.isAuthenticated.mockResolvedValue(false);

await act(async () => {
render(
Expand All @@ -363,8 +363,8 @@ describe('Context', () => {
);
});

await waitFor(() => expect(loginWithRedirect).toBeCalledTimes(1));
expect(loginWithRedirect).toBeCalledWith({
await waitFor(() => expect(clientMock.loginWithRedirect).toBeCalledTimes(1));
expect(clientMock.loginWithRedirect).toBeCalledWith({
authorizationParams: {
invitation,
organization,
Expand Down Expand Up @@ -412,7 +412,7 @@ describe('Context', () => {
writable: true,
});

isAuthenticated.mockResolvedValue(false);
clientMock.isAuthenticated.mockResolvedValue(false);

render(
<Organizations>
Expand All @@ -422,14 +422,8 @@ describe('Context', () => {
</Organizations>
);

await waitFor(() => expect(screen.getByTestId('isLoading').innerHTML).toBe('false'));
await waitFor(() => expect(loginWithRedirect).toBeCalledTimes(1));
expect(loginWithRedirect).toBeCalledWith({
authorizationParams: {
organization: organizationList[0].org_id,
invitation: undefined,
},
});
await waitFor(() => expect(screen.getByTestId('isLoading').innerHTML).toBe('true'));
await waitFor(() => expect(clientMock.logout).toBeCalledTimes(1));
}, 10000);

test('Context default functions', async () => {
Expand Down
10 changes: 5 additions & 5 deletions src/__tests__/Routing.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ const structure: RoutingStructure = {
],
};

xtest('authorized url access while authenticated', async () => {
test('authorized url access while authenticated', async () => {
const history = createMemoryHistory({ initialEntries: ['/authorized'] });

render(
Expand All @@ -50,7 +50,7 @@ xtest('authorized url access while authenticated', async () => {
expect(screen.getByText(/authorized/i)).toBeTruthy();
});

xtest('unauthorized access with redirection to unauthorized fallback while authenticated', async () => {
test('unauthorized access with redirection to unauthorized fallback while authenticated', async () => {
const history = createMemoryHistory({ initialEntries: ['/unauthorized'] });

render(
Expand All @@ -66,7 +66,7 @@ xtest('unauthorized access with redirection to unauthorized fallback while authe
expect(history.location.pathname).toBe(structure.fallbackPaths?.unauthorized);
});

xtest('anonymous access while authenticated. Redirection to authenticated but anonymous fallback', async () => {
test('anonymous access while authenticated. Redirection to authenticated but anonymous fallback', async () => {
const history = createMemoryHistory({ initialEntries: ['/open-page'] });

render(
Expand All @@ -82,7 +82,7 @@ xtest('anonymous access while authenticated. Redirection to authenticated but an
expect(history.location.pathname).toBe(structure.fallbackPaths?.authenticatedButAnonymous);
});

xtest('access to unknown path. Redirection to not found', async () => {
test('access to unknown path. Redirection to not found', async () => {
const history = createMemoryHistory({ initialEntries: ['/unknown-path'] });

render(
Expand All @@ -98,7 +98,7 @@ xtest('access to unknown path. Redirection to not found', async () => {
expect(screen.getByText(/page not found/i)).toBeTruthy();
});

xtest('unauthenticated access with redirection to unauthenticated fallback while NOT authenticated', async () => {
test('unauthenticated access with redirection to unauthenticated fallback while NOT authenticated', async () => {
const history = createMemoryHistory({ initialEntries: ['/unauthorized'] });

render(
Expand Down
Loading

0 comments on commit 402fd6f

Please sign in to comment.