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 numberDiff line numberDiff 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: 'foo@bar.com', page })
})
```
16 changes: 16 additions & 0 deletions packages/clerk-js/sandbox/integration/helpers.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,3 +19,19 @@ export async function signInWithEmailCode(page: Page): Promise<void> {
signInParams: { strategy: 'email_code', identifier: 'sandbox+clerk_test@clerk.dev' },
});
}

/**
* 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 = 'sandbox+clerk_test@clerk.dev'): 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 numberDiff line numberDiff 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: 'sandbox+clerk_test@clerk.dev',
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('sandbox+clerk_test@clerk.dev');
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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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. your_email+clerk_test@example.com).
*
* @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: "bryce@clerk.dev", 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
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 numberDiff line numberDiff 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: 'foo@bar.com', page })
})
```
16 changes: 16 additions & 0 deletions packages/clerk-js/sandbox/integration/helpers.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,3 +19,19 @@ export async function signInWithEmailCode(page: Page): Promise<void> {
signInParams: { strategy: 'email_code', identifier: 'sandbox+clerk_test@clerk.dev' },
});
}

/**
* 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 = 'sandbox+clerk_test@clerk.dev'): 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 numberDiff line numberDiff 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: 'sandbox+clerk_test@clerk.dev',
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('sandbox+clerk_test@clerk.dev');
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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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. your_email+clerk_test@example.com).
*
* @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: "bryce@clerk.dev", 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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 numberDiff line numberDiff 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: 'foo@bar.com', page })
})
```
16 changes: 16 additions & 0 deletions packages/clerk-js/sandbox/integration/helpers.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,3 +19,19 @@ export async function signInWithEmailCode(page: Page): Promise<void> {
signInParams: { strategy: 'email_code', identifier: 'sandbox+clerk_test@clerk.dev' },
});
}

/**
* 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 = 'sandbox+clerk_test@clerk.dev'): 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 numberDiff line numberDiff 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: 'sandbox+clerk_test@clerk.dev',
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('sandbox+clerk_test@clerk.dev');
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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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. your_email+clerk_test@example.com).
*
* @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: "bryce@clerk.dev", 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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 numberDiff line numberDiff 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: 'foo@bar.com', page })
})
```
16 changes: 16 additions & 0 deletions packages/clerk-js/sandbox/integration/helpers.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,3 +19,19 @@ export async function signInWithEmailCode(page: Page): Promise<void> {
signInParams: { strategy: 'email_code', identifier: 'sandbox+clerk_test@clerk.dev' },
});
}

/**
* 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 = 'sandbox+clerk_test@clerk.dev'): 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 numberDiff line numberDiff 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: 'sandbox+clerk_test@clerk.dev',
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('sandbox+clerk_test@clerk.dev');
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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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. your_email+clerk_test@example.com).
*
* @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: "bryce@clerk.dev", 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
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 numberDiff line numberDiff 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: 'foo@bar.com', page })
})
```
16 changes: 16 additions & 0 deletions packages/clerk-js/sandbox/integration/helpers.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,3 +19,19 @@ export async function signInWithEmailCode(page: Page): Promise<void> {
signInParams: { strategy: 'email_code', identifier: 'sandbox+clerk_test@clerk.dev' },
});
}

/**
* 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 = 'sandbox+clerk_test@clerk.dev'): 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 numberDiff line numberDiff 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: 'sandbox+clerk_test@clerk.dev',
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('sandbox+clerk_test@clerk.dev');
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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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. your_email+clerk_test@example.com).
*
* @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: "bryce@clerk.dev", 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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 numberDiff line numberDiff 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: 'foo@bar.com', page })
})
```
16 changes: 16 additions & 0 deletions packages/clerk-js/sandbox/integration/helpers.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,3 +19,19 @@ export async function signInWithEmailCode(page: Page): Promise<void> {
signInParams: { strategy: 'email_code', identifier: 'sandbox+clerk_test@clerk.dev' },
});
}

/**
* 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 = 'sandbox+clerk_test@clerk.dev'): 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 numberDiff line numberDiff 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: 'sandbox+clerk_test@clerk.dev',
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('sandbox+clerk_test@clerk.dev');
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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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. your_email+clerk_test@example.com).
*
* @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: "bryce@clerk.dev", 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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 numberDiff line numberDiff 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: 'foo@bar.com', page })
})
```
16 changes: 16 additions & 0 deletions packages/clerk-js/sandbox/integration/helpers.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,3 +19,19 @@ export async function signInWithEmailCode(page: Page): Promise<void> {
signInParams: { strategy: 'email_code', identifier: 'sandbox+clerk_test@clerk.dev' },
});
}

/**
* 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 = 'sandbox+clerk_test@clerk.dev'): 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 numberDiff line numberDiff 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: 'sandbox+clerk_test@clerk.dev',
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('sandbox+clerk_test@clerk.dev');
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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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. your_email+clerk_test@example.com).
*
* @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: "bryce@clerk.dev", 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 DownExpand 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
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
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 numberDiff line numberDiff 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: 'foo@bar.com', page })
})
```
16 changes: 16 additions & 0 deletions packages/clerk-js/sandbox/integration/helpers.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,3 +19,19 @@ export async function signInWithEmailCode(page: Page): Promise<void> {
signInParams: { strategy: 'email_code', identifier: 'sandbox+clerk_test@clerk.dev' },
});
}

/**
* 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 = 'sandbox+clerk_test@clerk.dev'): 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 numberDiff line numberDiff 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: 'sandbox+clerk_test@clerk.dev',
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('sandbox+clerk_test@clerk.dev');
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 numberDiff line numberDiff 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 numberDiff line numberDiff 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 DownExpand 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 numberDiff line numberDiff 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 numberDiff line numberDiff 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. your_email+clerk_test@example.com).
*
* @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: "bryce@clerk.dev", 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 DownExpand 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