Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .changeset/easy-parrots-slide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
'@clerk/testing': minor
---

Introduce new helper to allow signing a user in via email address:

```ts
import { clerk } from '@clerk/testing/playwright'

test('sign in', async ({ page }) => {
await clerk.signIn({ emailAddress: '[email protected]', page })
})
```
16 changes: 16 additions & 0 deletions packages/clerk-js/sandbox/integration/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,19 @@ export async function signInWithEmailCode(page: Page): Promise<void> {
signInParams: { strategy: 'email_code', identifier: '[email protected]' },
});
}

/**
* Signs in a user using the new email-based ticket strategy for integration tests.
* Finds the user by email, creates a sign-in token, and uses the ticket strategy.
* @param page - The Playwright page instance
* @param emailAddress - The email address of the user to sign in (defaults to sandbox test user)
* @example
* ```ts
* await signInWithEmail(page);
* await page.goto('/protected-page');
* ```
*/
export async function signInWithEmail(page: Page, emailAddress = '[email protected]'): Promise<void> {
await page.goto('/sign-in');
await clerk.signIn({ emailAddress, page });
}
23 changes: 23 additions & 0 deletions packages/clerk-js/sandbox/integration/sign-in.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,26 @@ test('sign in', async ({ page }) => {
await page.locator(actionLinkElement).hover();
await expect(page.locator(rootElement)).toHaveScreenshot('sign-in-action-link-hover.png');
});

test('sign in with email', async ({ page }) => {
await page.goto('/sign-in');

await clerk.signIn({
emailAddress: '[email protected]',
page,
});

await page.waitForFunction(() => window.Clerk?.user !== null);

const userInfo = await page.evaluate(() => ({
isSignedIn: window.Clerk?.user !== null && window.Clerk?.user !== undefined,
email: window.Clerk?.user?.primaryEmailAddress?.emailAddress,
userId: window.Clerk?.user?.id,
isLoaded: window.Clerk?.loaded,
}));

expect(userInfo.isSignedIn).toBe(true);
expect(userInfo.email).toBe('[email protected]');
expect(userInfo.userId).toBeTruthy();
expect(userInfo.isLoaded).toBe(true);
});
134 changes: 95 additions & 39 deletions packages/testing/src/common/helpers-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,58 +9,114 @@ export const signInHelper = async ({ signInParams, windowObject }: SignInHelperP
if (!w.Clerk.client) {
return;
}

const signIn = w.Clerk.client.signIn;
if (signInParams.strategy === 'password') {
const res = await signIn.create(signInParams);
await w.Clerk.setActive({
session: res.createdSessionId,
});
} else {
// Assert that the identifier is a test email or phone number
if (signInParams.strategy === 'phone_code' && !/^\+1\d{3}55501\d{2}$/.test(signInParams.identifier)) {
throw new Error(
`Phone number should be a test phone number.\n

switch (signInParams.strategy) {
case 'password': {
const res = await signIn.create(signInParams);
await w.Clerk.setActive({
session: res.createdSessionId,
});
break;
}

case 'ticket': {
const res = await signIn.create({
strategy: 'ticket',
ticket: signInParams.ticket,
});

if (res.status === 'complete') {
await w.Clerk.setActive({
session: res.createdSessionId,
});
} else {
throw new Error(`Sign-in with ticket failed. Status: ${res.status}`);
}
break;
}

case 'phone_code': {
// Assert that the identifier is a test phone number
if (!/^\+1\d{3}55501\d{2}$/.test(signInParams.identifier)) {
throw new Error(
`Phone number should be a test phone number.\n
Example: +1XXX55501XX.\n
Learn more here: https://clerk.com/docs/testing/test-emails-and-phones#phone-numbers`,
);
}

// Sign in with phone code
const { supportedFirstFactors } = await signIn.create({
identifier: signInParams.identifier,
});
const phoneFactor = supportedFirstFactors?.find(
(factor: SignInFirstFactor): factor is PhoneCodeFactor => factor.strategy === 'phone_code',
);

if (phoneFactor) {
await signIn.prepareFirstFactor({
strategy: 'phone_code',
phoneNumberId: phoneFactor.phoneNumberId,
});
const signInAttempt = await signIn.attemptFirstFactor({
strategy: 'phone_code',
code: '424242',
});

if (signInAttempt.status === 'complete') {
await w.Clerk.setActive({ session: signInAttempt.createdSessionId });
} else {
throw new Error(`Status is ${signInAttempt.status}`);
}
} else {
throw new Error('phone_code is not enabled.');
}
break;
}
if (signInParams.strategy === 'email_code' && !signInParams.identifier.includes('+clerk_test')) {
throw new Error(
`Email should be a test email.\n

case 'email_code': {
// Assert that the identifier is a test email
if (!signInParams.identifier.includes('+clerk_test')) {
throw new Error(
`Email should be a test email.\n
Any email with the +clerk_test subaddress is a test email address.\n
Learn more here: https://clerk.com/docs/testing/test-emails-and-phones#email-addresses`,
);
}

// Sign in with code (email_code or phone_code)
const { supportedFirstFactors } = await signIn.create({
identifier: signInParams.identifier,
});
const codeFactorFn =
signInParams.strategy === 'phone_code'
? (factor: SignInFirstFactor): factor is PhoneCodeFactor => factor.strategy === 'phone_code'
: (factor: SignInFirstFactor): factor is EmailCodeFactor => factor.strategy === 'email_code';
const codeFactor = supportedFirstFactors?.find(codeFactorFn);
if (codeFactor) {
const prepareParams =
signInParams.strategy === 'phone_code'
? { strategy: signInParams.strategy, phoneNumberId: (codeFactor as PhoneCodeFactor).phoneNumberId }
: { strategy: signInParams.strategy, emailAddressId: (codeFactor as EmailCodeFactor).emailAddressId };
);
}

await signIn.prepareFirstFactor(prepareParams);
const signInAttempt = await signIn.attemptFirstFactor({
strategy: signInParams.strategy,
code: '424242',
// Sign in with email code
const { supportedFirstFactors } = await signIn.create({
identifier: signInParams.identifier,
});
const emailFactor = supportedFirstFactors?.find(
(factor: SignInFirstFactor): factor is EmailCodeFactor => factor.strategy === 'email_code',
);

if (emailFactor) {
await signIn.prepareFirstFactor({
strategy: 'email_code',
emailAddressId: emailFactor.emailAddressId,
});
const signInAttempt = await signIn.attemptFirstFactor({
strategy: 'email_code',
code: '424242',
});

if (signInAttempt.status === 'complete') {
await w.Clerk.setActive({ session: signInAttempt.createdSessionId });
if (signInAttempt.status === 'complete') {
await w.Clerk.setActive({ session: signInAttempt.createdSessionId });
} else {
throw new Error(`Status is ${signInAttempt.status}`);
}
} else {
throw new Error(`Status is ${signInAttempt.status}`);
throw new Error('email_code is not enabled.');
}
} else {
throw new Error(`${signInParams.strategy} is not enabled.`);
break;
}

default:
throw new Error(`Unsupported strategy: ${(signInParams as any).strategy}`);
}
} catch (err: any) {
throw new Error(`Clerk: Failed to sign in: ${err?.message}`);
Expand Down
8 changes: 1 addition & 7 deletions packages/testing/src/common/setup.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createClerkClient } from '@clerk/backend';
import { isProductionFromSecretKey, parsePublishableKey } from '@clerk/shared/keys';
import { parsePublishableKey } from '@clerk/shared/keys';
import dotenv from 'dotenv';

import type { ClerkSetupOptions, ClerkSetupReturn } from './types';
Expand Down Expand Up @@ -39,12 +39,6 @@ export const fetchEnvVars = async (options?: ClerkSetupOptions): Promise<ClerkSe
}

if (secretKey && !testingToken) {
if (isProductionFromSecretKey(secretKey)) {
throw new Error(
'You are using a secret key from a production instance, but Testing Tokens only work in development instances.',
);
}

log('Fetching testing token from Clerk Backend API...');

try {
Expand Down
4 changes: 4 additions & 0 deletions packages/testing/src/common/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,10 @@ export type ClerkSignInParams =
| {
strategy: 'phone_code' | 'email_code';
identifier: string;
}
| {
strategy: 'ticket';
ticket: string;
};

export type SignInHelperParams = {
Expand Down
90 changes: 75 additions & 15 deletions packages/testing/src/playwright/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { createClerkClient } from '@clerk/backend';
import type { Clerk, SignOutOptions } from '@clerk/types';
import type { Page } from '@playwright/test';

Expand All @@ -15,36 +16,55 @@ type PlaywrightClerkLoadedParams = {
page: Page;
};

type PlaywrightClerkSignInParamsWithEmail = {
page: Page;
emailAddress: string;
setupClerkTestingTokenOptions?: SetupClerkTestingTokenOptions;
};

type ClerkHelperParams = {
/**
* Signs in a user using Clerk. This helper supports only password, phone_code and email_code first factor strategies.
* Signs in a user using Clerk. This helper supports multiple sign-in strategies:
* 1. Using signInParams object (password, phone_code, email_code strategies)
* 2. Using emailAddress for automatic ticket-based sign-in
*
* Multi-factor is not supported.
* This helper is using the `setupClerkTestingToken` internally.
* It is required to call `page.goto` before calling this helper, and navigate to a not protected page that loads Clerk.
*
* For strategy-based sign-in:
* If the strategy is password, the helper will sign in the user using the provided password and identifier.
* If the strategy is phone_code, you are required to have a user with a test phone number as an identifier (e.g. +15555550100).
* If the strategy is email_code, you are required to have a user with a test email as an identifier (e.g. [email protected]).
*
* @param opts.signInParams.strategy - The sign in strategy. Supported strategies are 'password', 'phone_code' and 'email_code'.
* @param opts.signInParams.identifier - The user's identifier. Could be a username, a phone number or an email.
* @param opts.signInParams.password - The user's password. Required only if the strategy is 'password'.
* @param opts.page - The Playwright page object.
* @param opts.setupClerkTestingTokenOptions - The options for the `setupClerkTestingToken` function. Optional.
* For email-based sign-in:
* The helper finds the user by email, creates a sign-in token using Clerk's backend API, and uses the ticket strategy.
*
* @example
* @example Strategy-based sign-in
* import { clerk } from "@clerk/testing/playwright";
*
* test("sign in", async ({ page }) => {
* test("sign in with strategy", async ({ page }) => {
* await page.goto("/");
* await clerk.signIn({
* page,
* signInParams: { strategy: 'phone_code', identifier: '+15555550100' },
* });
* await page.goto("/protected");
* });
*
* @example Email-based sign-in
* import { clerk } from "@clerk/testing/playwright";
*
* test("sign in with email", async ({ page }) => {
* await page.goto("/");
* await clerk.signIn({ emailAddress: "[email protected]", page });
* await page.goto("/protected");
* });
*/
signIn: (opts: PlaywrightClerkSignInParams) => Promise<void>;
signIn: {
(opts: PlaywrightClerkSignInParams): Promise<void>;
(opts: PlaywrightClerkSignInParamsWithEmail): Promise<void>;
};
/**
* Signs out the current user using Clerk.
* It is required to call `page.goto` before calling this helper, and navigate to a page that loads Clerk.
Expand Down Expand Up @@ -87,16 +107,56 @@ type PlaywrightClerkSignInParams = {
setupClerkTestingTokenOptions?: SetupClerkTestingTokenOptions;
};

const signIn = async ({ page, signInParams, setupClerkTestingTokenOptions }: PlaywrightClerkSignInParams) => {
const context = page.context();
const signIn = async (opts: PlaywrightClerkSignInParams | PlaywrightClerkSignInParamsWithEmail) => {
const context = opts.page.context();
if (!context) {
throw new Error('Page context is not available. Make sure the page is properly initialized.');
}

await setupClerkTestingToken({ context, options: setupClerkTestingTokenOptions });
await loaded({ page });
await setupClerkTestingToken({
context,
options: 'setupClerkTestingTokenOptions' in opts ? opts.setupClerkTestingTokenOptions : undefined,
});
await loaded({ page: opts.page });

if ('emailAddress' in opts) {
// Email-based sign-in using ticket strategy
const { emailAddress, page } = opts;

const secretKey = process.env.CLERK_SECRET_KEY;
if (!secretKey) {
throw new Error('CLERK_SECRET_KEY environment variable is required for email-based sign-in');
}

const clerkClient = createClerkClient({ secretKey });

await page.evaluate(signInHelper, { signInParams });
try {
// Find user by email
const userList = await clerkClient.users.getUserList({ emailAddress: [emailAddress] });
if (!userList.data || userList.data.length === 0) {
throw new Error(`No user found with email: ${emailAddress}`);
}

const user = userList.data[0];

const signInToken = await clerkClient.signInTokens.createSignInToken({
userId: user.id,
expiresInSeconds: 300, // 5 minutes
});

await page.evaluate(signInHelper, {
signInParams: { strategy: 'ticket' as const, ticket: signInToken.token },
});

await page.waitForFunction(() => window.Clerk?.user !== null);
} catch (err: any) {
throw new Error(`Failed to sign in with email ${emailAddress}: ${err?.message}`);
}
} else {
// Strategy-based sign-in: signIn(opts)
const { page, signInParams } = opts;
await page.evaluate(signInHelper, { signInParams });
}
};

type PlaywrightClerkSignOutParams = {
Expand All @@ -113,7 +173,7 @@ const signOut = async ({ page, signOutOptions }: PlaywrightClerkSignOutParams) =
};

export const clerk: ClerkHelperParams = {
signIn,
signIn: signIn as ClerkHelperParams['signIn'],
signOut,
loaded,
};
Loading