Skip to content

Commit 0c857cb

Browse files
committed
Adjust unit tests with newest API
1 parent ff4d1f3 commit 0c857cb

File tree

5 files changed

+73
-183
lines changed

5 files changed

+73
-183
lines changed

packages/clerk-js/src/core/__tests__/clerk.test.ts

Lines changed: 45 additions & 162 deletions
Original file line numberDiff line numberDiff line change
@@ -474,7 +474,6 @@ describe('Clerk singleton', () => {
474474
});
475475
});
476476

477-
// TODO -> Refactor tests
478477
describe('with `pending` session status', () => {
479478
const mockSession = {
480479
id: '1',
@@ -521,12 +520,53 @@ describe('Clerk singleton', () => {
521520

522521
const sut = new Clerk(productionPublishableKey);
523522
await sut.load();
524-
await sut.setActive({ session: mockSession as any as ActiveSessionResource });
523+
await sut.setActive({ session: mockSession as any as PendingSessionResource });
524+
expect(mockSession.touch).toHaveBeenCalled();
525+
});
526+
527+
it('calls `onPendingSession` from clerk options', async () => {
528+
mockSession.touch.mockReturnValue(Promise.resolve());
529+
mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSession] }));
530+
const onPendingSession = jest.fn();
531+
532+
const sut = new Clerk(productionPublishableKey);
533+
await sut.load({
534+
onPendingSession,
535+
});
536+
await sut.setActive({ session: mockSession as any as PendingSessionResource });
537+
expect(mockSession.touch).toHaveBeenCalled();
538+
expect(onPendingSession).toHaveBeenCalled();
539+
});
540+
541+
it('calls `onPendingSession` as argument', async () => {
542+
mockSession.touch.mockReturnValue(Promise.resolve());
543+
mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSession] }));
544+
const onPendingSession = jest.fn();
545+
546+
const sut = new Clerk(productionPublishableKey);
547+
await sut.load();
548+
await sut.setActive({ session: mockSession as any as PendingSessionResource, onPendingSession });
549+
expect(mockSession.touch).toHaveBeenCalled();
550+
expect(onPendingSession).toHaveBeenCalled();
551+
});
552+
553+
it('if `onPendingSession` is not defined, navigate to `taskUrl` option', async () => {
554+
mockSession.touch.mockReturnValue(Promise.resolve());
555+
mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSession] }));
556+
557+
const sut = new Clerk(productionPublishableKey);
558+
sut.navigate = jest.fn();
559+
await sut.load({
560+
taskUrls: {
561+
'choose-organization': '/choose-organization',
562+
},
563+
});
564+
await sut.setActive({ session: mockSession as any as PendingSessionResource });
525565
expect(mockSession.touch).toHaveBeenCalled();
566+
expect(sut.navigate).toHaveBeenCalledWith('/choose-organization');
526567
});
527568
});
528569

529-
// TODO -> Refactor tests
530570
describe('with force organization selection enabled', () => {
531571
const mockSession = {
532572
id: '1',
@@ -909,7 +949,7 @@ describe('Clerk singleton', () => {
909949
mockEnvironmentFetch.mockReset();
910950
});
911951

912-
describe('with after-auth flows', () => {
952+
describe('with pending session', () => {
913953
beforeEach(() => {
914954
mockClientFetch.mockReset();
915955
mockEnvironmentFetch.mockReturnValue(
@@ -926,7 +966,7 @@ describe('Clerk singleton', () => {
926966
);
927967
});
928968

929-
it('redirects to pending task', async () => {
969+
it('navigates to task', async () => {
930970
const mockSession = {
931971
id: '1',
932972
status: 'pending',
@@ -956,7 +996,6 @@ describe('Clerk singleton', () => {
956996
}),
957997
);
958998

959-
const mockSetActive = jest.fn();
960999
const mockSignUpCreate = jest
9611000
.fn()
9621001
.mockReturnValue(Promise.resolve({ status: 'complete', createdSessionId: '123' }));
@@ -967,60 +1006,13 @@ describe('Clerk singleton', () => {
9671006
fail('we should always have a client');
9681007
}
9691008
sut.client.signUp.create = mockSignUpCreate;
970-
sut.setActive = mockSetActive;
9711009

9721010
await sut.handleRedirectCallback();
9731011

9741012
await waitFor(() => {
9751013
expect(mockNavigate.mock.calls[0][0]).toBe('/sign-in#/tasks/choose-organization');
9761014
});
9771015
});
978-
979-
it('redirects to after sign-in URL when task has been resolved', async () => {
980-
const mockSession = {
981-
id: '1',
982-
status: 'active',
983-
user: {},
984-
lastActiveToken: { getRawString: () => 'mocked-token' },
985-
};
986-
987-
const mockResource = {
988-
...mockSession,
989-
remove: jest.fn(),
990-
touch: jest.fn(() => Promise.resolve()),
991-
getToken: jest.fn(),
992-
reload: jest.fn(() => Promise.resolve(mockSession)),
993-
};
994-
995-
mockResource.touch.mockReturnValueOnce(Promise.resolve());
996-
mockClientFetch.mockReturnValue(
997-
Promise.resolve({
998-
signedInSessions: [mockResource],
999-
signIn: new SignIn(null),
1000-
signUp: new SignUp(null),
1001-
isEligibleForTouch: () => false,
1002-
}),
1003-
);
1004-
1005-
const mockSetActive = jest.fn();
1006-
const mockSignUpCreate = jest
1007-
.fn()
1008-
.mockReturnValue(Promise.resolve({ status: 'complete', createdSessionId: '123' }));
1009-
1010-
const sut = new Clerk(productionPublishableKey);
1011-
await sut.load(mockedLoadOptions);
1012-
if (!sut.client) {
1013-
fail('we should always have a client');
1014-
}
1015-
sut.client.signUp.create = mockSignUpCreate;
1016-
sut.setActive = mockSetActive;
1017-
1018-
await sut.handleRedirectCallback();
1019-
1020-
await waitFor(() => {
1021-
expect(mockNavigate.mock.calls[0][0]).toBe('/');
1022-
});
1023-
});
10241016
});
10251017

10261018
it('creates a new user and calls setActive if the user was not found during sso signup', async () => {
@@ -2434,115 +2426,6 @@ describe('Clerk singleton', () => {
24342426
});
24352427
});
24362428

2437-
describe('navigateToTask', () => {
2438-
describe('with `pending` session status', () => {
2439-
const mockSession = {
2440-
id: '1',
2441-
status: 'pending',
2442-
user: {},
2443-
tasks: [{ key: 'choose-organization' }],
2444-
currentTask: { key: 'choose-organization', __internal_getUrl: () => 'https://sut/tasks/choose-organization' },
2445-
lastActiveToken: { getRawString: () => 'mocked-token' },
2446-
};
2447-
2448-
const mockResource = {
2449-
...mockSession,
2450-
remove: jest.fn(),
2451-
touch: jest.fn(() => Promise.resolve()),
2452-
getToken: jest.fn(),
2453-
reload: jest.fn(() => Promise.resolve(mockSession)),
2454-
};
2455-
2456-
beforeEach(() => {
2457-
mockResource.touch.mockReturnValueOnce(Promise.resolve());
2458-
mockClientFetch.mockReturnValue(
2459-
Promise.resolve({
2460-
signedInSessions: [mockResource],
2461-
isEligibleForTouch: () => false,
2462-
}),
2463-
);
2464-
});
2465-
2466-
afterEach(() => {
2467-
mockResource.remove.mockReset();
2468-
mockResource.touch.mockReset();
2469-
});
2470-
2471-
it('navigates to next task with default internal routing for AIOs', async () => {
2472-
const sut = new Clerk(productionPublishableKey);
2473-
await sut.load(mockedLoadOptions);
2474-
2475-
await sut.setActive({ session: mockResource as any as PendingSessionResource });
2476-
2477-
expect(mockNavigate.mock.calls[0][0]).toBe('/sign-in#/tasks/choose-organization');
2478-
});
2479-
2480-
it('navigates to next task with custom routing from clerk options', async () => {
2481-
const sut = new Clerk(productionPublishableKey);
2482-
await sut.load({
2483-
...mockedLoadOptions,
2484-
taskUrls: {
2485-
'choose-organization': '/onboarding/choose-organization',
2486-
},
2487-
});
2488-
2489-
await sut.setActive({ session: mockResource as any as PendingSessionResource });
2490-
2491-
expect(mockNavigate.mock.calls[0][0]).toBe('/onboarding/choose-organization');
2492-
});
2493-
});
2494-
2495-
describe('with `active` session status', () => {
2496-
const mockSession = {
2497-
id: '1',
2498-
remove: jest.fn(),
2499-
status: 'active',
2500-
user: {},
2501-
touch: jest.fn(() => Promise.resolve()),
2502-
getToken: jest.fn(),
2503-
lastActiveToken: { getRawString: () => 'mocked-token' },
2504-
reload: jest.fn(() =>
2505-
Promise.resolve({
2506-
id: '1',
2507-
remove: jest.fn(),
2508-
status: 'active',
2509-
user: {},
2510-
touch: jest.fn(() => Promise.resolve()),
2511-
getToken: jest.fn(),
2512-
lastActiveToken: { getRawString: () => 'mocked-token' },
2513-
}),
2514-
),
2515-
};
2516-
2517-
afterEach(() => {
2518-
mockSession.remove.mockReset();
2519-
mockSession.touch.mockReset();
2520-
(window as any).__unstable__onBeforeSetActive = null;
2521-
(window as any).__unstable__onAfterSetActive = null;
2522-
});
2523-
2524-
it('navigates to redirect url on completion', async () => {
2525-
mockSession.touch.mockReturnValue(Promise.resolve());
2526-
mockClientFetch.mockReturnValue(
2527-
Promise.resolve({
2528-
signedInSessions: [mockSession],
2529-
isEligibleForTouch: () => false,
2530-
}),
2531-
);
2532-
2533-
const sut = new Clerk(productionPublishableKey);
2534-
await sut.load(mockedLoadOptions);
2535-
await sut.setActive({ session: mockSession as any as ActiveSessionResource });
2536-
2537-
const redirectUrlComplete = '/welcome-to-app';
2538-
2539-
console.log(mockNavigate.mock.calls);
2540-
2541-
expect(mockNavigate.mock.calls[0][0]).toBe('/welcome-to-app');
2542-
});
2543-
});
2544-
});
2545-
25462429
describe('updateClient', () => {
25472430
afterEach(() => {
25482431
// cleanup global window pollution

packages/clerk-js/src/core/clerk.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,9 @@ import type {
2828
AuthenticateWithGoogleOneTapParams,
2929
AuthenticateWithMetamaskParams,
3030
AuthenticateWithOKXWalletParams,
31+
Clerk as ClerkInterface,
3132
ClerkAPIError,
3233
ClerkAuthenticateWithWeb3Params,
33-
Clerk as ClerkInterface,
3434
ClerkOptions,
3535
ClientJSONSnapshot,
3636
ClientResource,
@@ -429,10 +429,6 @@ export class Clerk implements ClerkInterface {
429429

430430
assertNoLegacyProp(this.#options);
431431

432-
if (this.__internal_hasAfterAuthFlows) {
433-
warnNoTaskOptions(this.#options);
434-
}
435-
436432
if (this.#options.sdkMetadata) {
437433
Clerk.sdkMetadata = this.#options.sdkMetadata;
438434
}
@@ -1268,6 +1264,10 @@ export class Clerk implements ClerkInterface {
12681264
}
12691265

12701266
if (newSession?.status === 'pending') {
1267+
warnNoTaskOptions({
1268+
...this.#options,
1269+
onPendingSession: this.#options['onPendingSession'] ?? onPendingSession,
1270+
});
12711271
await this.#handlePendingSession(newSession, onPendingSession);
12721272
return;
12731273
}
@@ -1362,7 +1362,7 @@ export class Clerk implements ClerkInterface {
13621362
if (currentSession.status === 'pending') {
13631363
const tracker = createBeforeUnloadTracker(this.#options.standardBrowser);
13641364

1365-
const onPendingSessionHook = this.#options['onPendingSession'] ?? onPendingSession;
1365+
const onPendingSessionHook = onPendingSession ?? this.#options['onPendingSession'];
13661366
const taskUrls = this.#options['taskUrls'];
13671367

13681368
await tracker.track(async () => {

packages/clerk-js/src/core/sessionTasks.ts

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,16 @@ import type { ClerkOptions, PendingSessionResource, SessionTask } from '@clerk/t
22

33
import { buildURL } from '../utils';
44

5+
/**
6+
* @internal
7+
*/
58
export const INTERNAL_SESSION_TASK_ROUTE_BY_KEY: Record<SessionTask['key'], string> = {
69
'choose-organization': 'choose-organization',
710
} as const;
811

9-
interface NavigateToTaskOptions {
10-
navigate: (to: string) => Promise<unknown>;
11-
baseUrl: string;
12-
options?: ClerkOptions;
13-
}
14-
12+
/**
13+
* @internal
14+
*/
1515
export function buildTaskURL(task: SessionTask, opts: Pick<Parameters<typeof buildURL>[0], 'base'>) {
1616
return buildURL(
1717
{
@@ -25,7 +25,18 @@ export function buildTaskURL(task: SessionTask, opts: Pick<Parameters<typeof bui
2525
/**
2626
* @internal
2727
*/
28-
export function navigateToTask(session: PendingSessionResource, { options, navigate, baseUrl }: NavigateToTaskOptions) {
28+
export function navigateToTask(
29+
session: PendingSessionResource,
30+
{
31+
options,
32+
navigate,
33+
baseUrl,
34+
}: {
35+
navigate: (to: string) => Promise<unknown>;
36+
baseUrl: string;
37+
options?: ClerkOptions;
38+
},
39+
) {
2940
const currentTaskKey = session.currentTask.key;
3041

3142
return navigate(options?.taskUrls?.[currentTaskKey] ?? buildTaskURL(session.currentTask, { base: baseUrl }));
Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,3 @@
1-
import {
2-
SSOCallback,
3-
withRedirectToAfterSignUp,
4-
withRedirectToSignUpTask,
5-
withRedirectToSignUpTask,
6-
} from '../../common';
1+
import { SSOCallback, withRedirectToAfterSignUp, withRedirectToSignUpTask } from '../../common';
72

83
export const SignUpSSOCallback = withRedirectToSignUpTask(withRedirectToAfterSignUp(SSOCallback));

packages/clerk-js/src/ui/contexts/components/SignIn.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -122,10 +122,11 @@ export const useSignInContext = (): SignInContextType => {
122122

123123
const onPendingSession: OnPendingSessionFn = async ({ session }) => {
124124
const currentTaskKey = session.currentTask.key;
125+
const customTaskUrl = clerk.__internal_getOption('taskUrls')?.[currentTaskKey];
125126

126127
switch (currentTaskKey) {
127128
case 'choose-organization': {
128-
await navigate(`../tasks/${currentTaskKey}`);
129+
await navigate(customTaskUrl ?? `../tasks/${currentTaskKey}`);
129130
}
130131
}
131132
};
@@ -136,7 +137,7 @@ export const useSignInContext = (): SignInContextType => {
136137
: null;
137138

138139
return {
139-
...(ctx as SignInCtx),
140+
...ctx,
140141
transferable: ctx.transferable ?? true,
141142
oauthFlow: ctx.oauthFlow || 'auto',
142143
componentName,

0 commit comments

Comments
 (0)