Skip to content

fix(testing): Better route interception hierarchy #5673

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Apr 21, 2025
Merged
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
7 changes: 7 additions & 0 deletions .changeset/fruity-areas-train.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@clerk/testing': minor
---

Switching over our interception of FAPI calls from page.route to context.route as routes set up with page.route() take precedence over browser context routes when request matches both handlers.

This allows for users to override calls to FAPI more consistently
4 changes: 2 additions & 2 deletions integration/testUtils/index.ts
Original file line number Diff line number Diff line change
@@ -102,9 +102,9 @@ const createClerkUtils = ({ page }: TestArgs) => {
};
};

const createTestingTokenUtils = ({ page }: TestArgs) => {
const createTestingTokenUtils = ({ context }: TestArgs) => {
return {
setup: async () => setupClerkTestingToken({ page }),
setup: async () => setupClerkTestingToken({ context }),
};
};

4 changes: 2 additions & 2 deletions integration/tests/non-secure-context.test.ts
Original file line number Diff line number Diff line change
@@ -51,8 +51,8 @@ testAgainstRunningApps({ withPattern: ['next.appRouter.withEmailCodes'] })(
server.close();
});

test('sign-in flow', async ({ page }) => {
const u = createTestUtils({ app, page });
test('sign-in flow', async ({ context, page }) => {
const u = createTestUtils({ app, context, page });

await u.po.testingToken.setup();
await u.page.goto(`http://${APP_HOST}`, { timeout: 50000 });
6 changes: 2 additions & 4 deletions integration/tests/resiliency.test.ts
Original file line number Diff line number Diff line change
@@ -197,8 +197,7 @@ testAgainstRunningApps({ withEnv: [appConfigs.envs.withEmailCodes] })('resilienc
await expect(page.getByText('Clerk is loading', { exact: true })).toBeHidden();
});

// TODO: Fix detection of hotloaded clerk-js failing
test.skip('clerk-js client fails and status degraded', async ({ page, context }) => {
test('clerk-js client fails and status degraded', async ({ page, context }) => {
Copy link
Preview

Copilot AI Apr 20, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-enabling the test 'clerk-js client fails and status degraded' without addressing its known hotloading issues may lead to unstable behavior. Consider revisiting the underlying flakiness or adding proper conditions to mitigate intermittent failures.

Copilot uses AI. Check for mistakes.

const u = createTestUtils({ app, page, context });

await page.route('**/v1/client?**', route => route.fulfill(make500ClerkResponse()));
@@ -227,8 +226,7 @@ testAgainstRunningApps({ withEnv: [appConfigs.envs.withEmailCodes] })('resilienc
await expect(page.getByText('Clerk is loading', { exact: true })).toBeHidden();
});

// TODO: Fix flakiness when intercepting environment requests
test.skip('clerk-js environment fails and status degraded', async ({ page, context }) => {
test('clerk-js environment fails and status degraded', async ({ page, context }) => {
const u = createTestUtils({ app, page, context });

await page.route('**/v1/environment?**', route => route.fulfill(make500ClerkResponse()));
13 changes: 9 additions & 4 deletions integration/tests/reverification.test.ts
Original file line number Diff line number Diff line change
@@ -37,10 +37,15 @@ testAgainstRunningApps({ withEnv: [appConfigs.envs.withReverification] })(
});

test.afterAll(async () => {
await fakeOrganization.delete();
await fakeViewer.deleteIfExists();
await fakeAdmin.deleteIfExists();
await app.teardown();
try {
Copy link
Preview

Copilot AI Apr 20, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] While wrapping cleanup functions in a try-catch block prevents test failures during teardown, silently logging errors could mask underlying issues. Consider enhancing error reporting or re-throwing critical failures after logging.

Copilot uses AI. Check for mistakes.

await fakeOrganization.delete();
await fakeViewer.deleteIfExists();
await fakeAdmin.deleteIfExists();
} catch (error) {
console.error(error);
} finally {
await app.teardown();
}
});

test('reverification prompt on adding new email address', async ({ page, context }) => {
7 changes: 6 additions & 1 deletion packages/testing/src/playwright/helpers.ts
Original file line number Diff line number Diff line change
@@ -88,7 +88,12 @@ type PlaywrightClerkSignInParams = {
};

const signIn = async ({ page, signInParams, setupClerkTestingTokenOptions }: PlaywrightClerkSignInParams) => {
await setupClerkTestingToken({ page, options: setupClerkTestingTokenOptions });
const context = 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 page.evaluate(signInHelper, { signInParams });
21 changes: 15 additions & 6 deletions packages/testing/src/playwright/setupClerkTestingToken.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,46 @@
import type { Page } from '@playwright/test';
import type { BrowserContext, Page } from '@playwright/test';

import type { SetupClerkTestingTokenOptions } from '../common';
import { ERROR_MISSING_FRONTEND_API_URL, TESTING_TOKEN_PARAM } from '../common';

type SetupClerkTestingTokenParams = {
page: Page;
context?: BrowserContext;
page?: Page;
options?: SetupClerkTestingTokenOptions;
};

/**
* Bypasses bot protection by appending the testing token in the Frontend API requests.
*
* @param params.context - The Playwright browser context object.
* @param params.page - The Playwright page object.
* @param params.options.frontendApiUrl - The frontend API URL for your Clerk dev instance, without the protocol.
* @returns A promise that resolves when the bot protection bypass is set up.
* @throws An error if the Frontend API URL is not provided.
* @example
* import { setupClerkTestingToken } from '@clerk/testing/playwright';
*
* test('should bypass bot protection', async ({ page }) => {
* await setupClerkTestingToken({ page });
* test('should bypass bot protection', async ({ context }) => {
* await setupClerkTestingToken({ context });
* const page = await context.newPage();
* await page.goto('https://your-app.com');
* // Continue with your test...
* });
*/
export const setupClerkTestingToken = async ({ page, options }: SetupClerkTestingTokenParams) => {
export const setupClerkTestingToken = async ({ context, options, page }: SetupClerkTestingTokenParams) => {
const browserContext = context ?? page?.context();

if (!browserContext) {
throw new Error('Either context or page must be provided to setup testing token');
}

const fapiUrl = options?.frontendApiUrl || process.env.CLERK_FAPI;
if (!fapiUrl) {
throw new Error(ERROR_MISSING_FRONTEND_API_URL);
}
const apiUrl = `https://${fapiUrl}/v1/**/*`;

await page.route(apiUrl, async route => {
await browserContext.route(apiUrl, async route => {
const originalUrl = new URL(route.request().url());
const testingToken = process.env.CLERK_TESTING_TOKEN;

1 change: 1 addition & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.