Docs

Testing with Cypress

Warning

Our @clerk/testing package only supports end-to-end testing. Unit tests are not supported.

Testing with Cypress requires the use of Testing Tokens to bypass various bot detection mechanisms that typically safeguard Clerk apps against malicious bots. Without Testing Tokens, you might encounter "Bot traffic detected" errors in your requests.

This guide will help you set up your environment for creating Clerk-authenticated tests with Cypress.

Important

Check out the demo repo that tests a Clerk-powered application using Testing Tokens.

Install @clerk/testing

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

terminal
npm install @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. In the Clerk Dashboard, navigate to the API Keys page.
  2. In the Quick Copy section, copy your Clerk publishable and secret key.
  3. Paste your keys into your .env.local file.

Warning

Ensure you provide the secret key in a secure manner, to avoid leaking it to third parties. For example, if you are using GitHub Actions, refer to Using secrets in GitHub Actions.

Global setup

To set up Clerk with Cypress, call the clerkSetup() function in your cypress.config.ts file.

cypress.config.ts
import { clerkSetup } from '@clerk/testing/cypress'
import { defineConfig } from 'cypress'

export default defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      return clerkSetup({ config })
    },
    baseUrl: 'http://localhost:3000', // your app's URL
  },
})

clerkSetup() will retrieve a Testing Token once the test suite starts, making it available for all subsequent tests.

Use Clerk Testing Tokens

Now that Cypress is configured with Clerk, use the setupClerkTestingToken() function in your tests to integrate the Testing Token. See the following example:

testing-tokens.cy.ts
import { setupClerkTestingToken } from '@clerk/testing/cypress'

it('sign up', () => {
  setupClerkTestingToken()

  cy.visit('/sign-up')
  // Add any other actions to test
})

Feedback

What did you think of this content?

Last updated on