Skip to content

Commit

Permalink
fix: testing for merged
Browse files Browse the repository at this point in the history
  • Loading branch information
panvourtsis authored and mkarajohn committed Feb 25, 2024
1 parent 23132b7 commit 429c52e
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 94 deletions.
109 changes: 38 additions & 71 deletions src/__tests__/Authentication.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,27 +13,19 @@ class CustomError extends Error {

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

import {
FAKE_TOKEN,
fakeTokenData,
getNewFakeToken,
getUser,
isAuthenticated,
loginWithRedirect,
logout,
Auth0Client as mockedCreateAuth0,
getTokenSilently as mockedGetTokenSilently,
handleRedirectCallback as mockedHandleRedirectCallback,
} from '__mocks__/@auth0/auth0-spa-js';
import { Auth0Client } from '@auth0/auth0-spa-js';
import { mocked } from 'ts-jest/utils';
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';
import { Organizations } from '~/providers/Organizations';
import MockRequest from '~/request/mock';
import MockRequest from '../request/mock';
import { orfiumIdBaseInstance } from '~/request';
import useOrganization from '~/store/organizations';
import useRequestToken from '~/store/requestToken';
import { getAuth0Client, getTokenSilently, logoutAuth, onRedirectCallback } from '~/utils/auth';
import useOrganization from '../store/organizations';
import useRequestToken from '../store/requestToken';
import { getTokenSilently, logoutAuth, onRedirectCallback } from '~/utils/auth';
const clientMock = mocked(new Auth0Client({ clientId: '', domain: '' }));

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

afterEach(() => {
Expand All @@ -110,9 +102,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 @@ -137,19 +129,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 @@ -164,14 +160,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 @@ -228,7 +224,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 @@ -271,7 +267,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 @@ -282,9 +278,9 @@ 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(),
});
Expand All @@ -303,7 +299,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 @@ -316,14 +312,16 @@ describe('Context', () => {
</ErrorBoundary>
);

await waitFor(() => expect(logout).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';

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 @@ -338,7 +336,7 @@ describe('Context', () => {
</ErrorBoundary>
);

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

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

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

await act(async () => {
render(
Expand All @@ -366,8 +364,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 @@ -415,7 +413,7 @@ describe('Context', () => {
writable: true,
});

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

render(
<Organizations>
Expand All @@ -426,7 +424,7 @@ describe('Context', () => {
);

await waitFor(() => expect(screen.getByTestId('isLoading').innerHTML).toBe('true'));
await waitFor(() => expect(logout).toBeCalledTimes(1));
await waitFor(() => expect(clientMock.logout).toBeCalledTimes(1));
}, 10000);

test('Context default functions', async () => {
Expand All @@ -437,35 +435,4 @@ describe('Context', () => {
expect(await defaultAuthenticationContextValues.logout()).toBe('logged out');
expect(await defaultAuthenticationContextValues.loginWithRedirect()).toBe(undefined);
});

test('getAuth0Client failed process', async () => {
expect.assertions(1);
mockedCreateAuth0.mockImplementation(() => {
throw new Error();
});
// @ts-ignore
client = undefined;
try {
getAuth0Client();
} catch (e) {
expect(e).toEqual(new Error(`getAuth0Client Error: Error`));
}
});

test('logoutAuth failed process', async () => {
expect.assertions(1);

// @ts-ignore
client = undefined;
// @ts-ignore make logout fail with no .logout property on client
mockedCreateAuth0.mockImplementation(() => {
return {};
});

try {
await logoutAuth();
} catch (e) {
expect(e).toEqual(new Error(`logoutAuth Error: client is not defined`));
}
});
});
39 changes: 16 additions & 23 deletions src/__tests__/check-that-getAuth0Client-throws-properly.test.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,22 @@
import { createAuth0Client as mockedCreateAuth0 } from '__mocks__/@auth0/auth0-spa-js';
import { getAuth0Client, logoutAuth } from '~/utils/auth';
import { getAuth0Client } from '~/utils/auth';

test('getAuth0Client failed process', async () => {
expect.assertions(1);
mockedCreateAuth0.mockImplementation(() => {
throw new Error();
describe('Auth0Client Errors Tests', () => {
beforeEach(() => {
jest.clearAllMocks();
});

try {
await getAuth0Client();
} catch (e) {
expect(e).toEqual(new Error(`getAuth0Client Error: Error`));
}
});
test('getAuth0Client failed process', async () => {
expect.assertions(1);

test('logoutAuth failed process', async () => {
expect.assertions(1);
// @ts-ignore make logout fail with no .logout property on client
mockedCreateAuth0.mockImplementation(() => {
return {};
});
// eslint-disable-next-line @typescript-eslint/no-var-requires
require('@auth0/auth0-spa-js').Auth0Client.mockImplementation(() => {
throw new Error();
});

try {
await logoutAuth();
} catch (e) {
expect(e).toEqual(new Error(`client_1.logout is not a function`));
}
try {
getAuth0Client(true);
} catch (e) {
expect(e).toEqual(new Error(`getAuth0Client Error: Error`));
}
});
});

0 comments on commit 429c52e

Please sign in to comment.