Docs

Testing with Playwright

Playwright is an open-source, end-to-end testing framework that automates web application testing across multiple browsers. This guide will help you set up your environment for creating authenticated tests with Clerk, assuming you have some familiarity with both Clerk and Playwright.

Important

See the demo repo that demonstrates testing a Clerk-powered application using Testing Tokens. To run the tests, you'll need dev instance Clerk API keys, a test user with username and password, and have username and password authentication enabled in the Clerk Dashboard.

Install @clerk/testing

Clerk's testing package provides integration helpers for popular testing frameworks. Run the following command to install it:

terminal
npm i @clerk/testing --save-dev
terminal
yarn add -D @clerk/testing
terminal
pnpm add @clerk/testing -D

Set your API keys

In your test runner, set your publishable and secret key as the CLERK_PUBLISHABLE_KEY and CLERK_SECRET_KEY environment variables, respectively.

To find your keys:

  1. Navigate to the Clerk Dashboard.
  2. In the top navbar, select Configure. In the sidebar, select API Keys.
  3. In the Quick Copy section, copy your Clerk publishable and secret key.

Warning

Ensure that the secret key is provided securely to prevent exposure to third parties. For example, if you are using GitHub Actions, refer to Using secrets in GitHub Actions.

Configure Playwright with Clerk

The clerkSetup() function obtains a Testing Token when your test suite starts, making it available for all subsequent tests to use. This ensures that you don't have to manually generate a Testing Token for each test.

To configure Playwright with Clerk, call the clerkSetup() function in your global setup file, as shown in the following example:

global.setup.ts
import { clerkSetup } from '@clerk/testing/playwright'
import { test as setup } from '@playwright/test'

setup('global setup', async ({}) => {
  await clerkSetup()
})

Note

You can manually set the Testing Token by using the CLERK_TESTING_TOKEN environment variable instead of calling clerkSetup().

Use setupClerkTestingToken()

Now that Playwright is configured with Clerk, you can use the setupClerkTestingToken() function to include the Testing Token in individual test cases. This function injects the Testing Token for the specific test, ensuring the test can bypass Clerk's bot detection mechanisms. See the following example:

my-test.spec.ts
import { setupClerkTestingToken } from '@clerk/testing/playwright'
import { test } from '@playwright/test'

test('sign up', async ({ page }) => {
  await setupClerkTestingToken({ page })

  await page.goto('/sign-up')
  // Add additional test logic here
})

Feedback

What did you think of this content?

Last updated on