Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
victoriaxyz committed Nov 15, 2024
2 parents 3ed549c + 4fbff20 commit 54fb35b
Show file tree
Hide file tree
Showing 5 changed files with 179 additions and 87 deletions.
21 changes: 20 additions & 1 deletion docs/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -977,7 +977,26 @@
]
]
},
{ "title": "Cypress", "href": "/docs/testing/cypress" },
{
"title": "Cypress",
"collapse": true,
"items": [
[
{
"title": "Overview",
"href": "/docs/testing/cypress/overview"
},
{
"title": "Custom commands",
"href": "/docs/testing/cypress/custom-commands"
},
{
"title": "Test Account Portal",
"href": "/docs/testing/cypress/test-account-portal"
}
]
]
},
{
"title": "Postman or Insomnia",
"href": "/docs/testing/postman-or-insomnia"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,89 +1,9 @@
---
title: Testing with Cypress
description: Use Cypress to write end-to-end tests with Clerk.
title: Custom commands
description: Use custom commands to sign in and out with Clerk in your Cypress tests.
---

> [!WARNING]
> Our `@clerk/testing` package only supports end-to-end testing. Unit tests are not supported.
Testing with Cypress requires the use of Clerk's [Testing Tokens](/docs/testing/overview#testing-tokens) to bypass various bot detection mechanisms that typically safeguard Clerk applications against malicious bots. Without Testing Tokens, you may encounter "Bot traffic detected" errors in your requests.

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

> [!IMPORTANT]
> See the [demo repo](https://github.com/clerk/clerk-cypress-nextjs) that tests a Clerk-powered application using [Testing Tokens](/docs/testing/overview#testing-tokens).
<Steps>
### Install `@clerk/testing`

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

<CodeBlockTabs options={['npm', 'yarn', 'pnpm']}>
```sh {{ filename: 'terminal' }}
npm i @clerk/testing --save-dev
```

```sh {{ filename: 'terminal' }}
yarn add -D @clerk/testing
```

```sh {{ filename: 'terminal' }}
pnpm add @clerk/testing -D
```
</CodeBlockTabs>

### 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](https://dashboard.clerk.com/last-active?path=api-keys).
1. In the navigation sidebar, select **API Keys**.
1. In the **Quick Copy** section, copy your Clerk publishable and secret key.

> [!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_](https://docs.github.com/en/actions/security-guides/using-secrets-in-github-actions).

### Global setup

To set up Clerk with Cypress, you must call the `clerkSetup()` function in your [`cypress.config.ts`](https://docs.cypress.io/guides/references/configuration) file.
```tsx filename="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 obtain a [Testing Token](/docs/testing/overview#testing-tokens) when your test suite starts, making it available for all subsequent tests to use.
### Use Clerk Testing Tokens
Now that Cypress is configured with Clerk, you can use the `setupClerkTestingToken()` function in your tests to augment them with the Testing Token. See the following example:
```tsx filename="my-test.cy.ts"
import { setupClerkTestingToken } from '@clerk/testing/cypress'
it('sign up', () => {
setupClerkTestingToken()

cy.visit('/sign-up')
// ...
})
```
</Steps>
## Custom Commands
The `@clerk/testing` package also provides [Cypress custom commands](https://docs.cypress.io/api/cypress-api/custom-commands) to sign in/sign out with Clerk in your Cypress tests without having to interact with the UI.
The `@clerk/testing` package provides [Cypress custom commands](https://docs.cypress.io/api/cypress-api/custom-commands) to sign in and out with Clerk in your Cypress tests without having to interact with the UI.
To use these commands, you must import them in your [Cypress E2E support file](https://docs.cypress.io/guides/core-concepts/writing-and-organizing-tests#Support-file), as shown in the following example.

```ts {{ filename: 'cypress/support/e2e.ts' }}
Expand Down Expand Up @@ -215,5 +135,3 @@ it('check Clerk loaded', () => {
// Clerk has been loaded from here on
})
```
For more information, feedback or issues, visit the [`@clerk/testing`](https://github.com/clerk/javascript/tree/main/packages/testing) package.
82 changes: 82 additions & 0 deletions docs/testing/cypress/overview.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
---
title: Testing with Cypress
description: Use Cypress to write end-to-end tests with Clerk.
---

> [!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](/docs/testing/overview#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](https://github.com/clerk/clerk-cypress-nextjs) that tests a Clerk-powered application using [Testing Tokens](/docs/testing/overview#testing-tokens).
<Steps>
### Install `@clerk/testing`

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

<CodeBlockTabs options={['npm', 'yarn', 'pnpm']}>
```sh {{ filename: 'terminal' }}
npm install @clerk/testing --save-dev
```

```sh {{ filename: 'terminal' }}
yarn add -D @clerk/testing
```

```sh {{ filename: 'terminal' }}
pnpm add @clerk/testing -D
```
</CodeBlockTabs>

### 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**](https://dashboard.clerk.com/last-active?path=api-keys) page.
1. In the **Quick Copy** section, copy your Clerk publishable and secret key.
1. 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_](https://docs.github.com/en/actions/security-guides/using-secrets-in-github-actions).

### Global setup

To set up Clerk with Cypress, call the `clerkSetup()` function in your [`cypress.config.ts`](https://docs.cypress.io/guides/references/configuration) file.
```tsx filename="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](/docs/testing/overview#testing-tokens) 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:
```tsx filename="testing-tokens.cy.ts"
import { setupClerkTestingToken } from '@clerk/testing/cypress'
it('sign up', () => {
setupClerkTestingToken()

cy.visit('/sign-up')
// Add any other actions to test
})
```
</Steps>
73 changes: 73 additions & 0 deletions docs/testing/cypress/test-account-portal.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
---
title: Test Account Portal flows
description: Learn how to test the Account Portal flow with Cypress.
---

Testing navigation flows with Cypress can be challenging, especially when redirects to external URLs are involved. This guide demonstrates how to use Cypress to test the Account Portal flow, including the redirect to the Account Portal and back to your app.

> [!IMPORTANT]
> Check out the [demo repo](https://github.com/clerk/clerk-cypress-nextjs) that demonstrates testing a Clerk-powered application using [Testing Tokens](/docs/testing/overview#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.
## Get your Account Portal domain

To get your Account Portal domain, go to the [**Account Portal**](https://dashboard.clerk.com/last-active?path=account-portal) page in the Clerk Dashboard. The domain format should resemble: `https://verb-noun-00.accounts.dev`

## The test format

Cypress's `cy.origin()` function lets you visit multiple domains of different origins in the same test. For more information, see the [Cypress documentation](https://docs.cypress.io/api/commands/origin).

By passing your Account Portal domain to `cy.origin()`, your test can navigate to the Account Portal domain and then return to your app.

Structure tests that include Account Portal redirects as follows:

```ts
it('sign in with Account Portal redirects', () => {
setupClerkTestingToken()

// Set the origin to the Account Portal domain
cy.origin('https://verb-noun-00.accounts.dev', () => {
// Visit a protected page that redirects to the Account Portal when not signed in
cy.visit('http://localhost:3000/protected')
// Fill the form to sign in
// Add any other actions to test
})

// The user should be redirected back to the protected page
cy.url().should('include', '/protected')
})
```

## Example

The following example creates a test that:

- visits a protected page, which redirects to the Account Portal when not signed in
- completes the form to sign in
- redirects back to the protected page

```ts
import { setupClerkTestingToken } from '@clerk/testing/cypress'

describe('Testing Tokens', () => {
it('sign in with Account Portal redirects', () => {
setupClerkTestingToken()

cy.origin('https://verb-noun-00.accounts.dev', () => {
cy.visit('http://localhost:3000/protected')
cy.contains('h1', 'Sign in')
cy.get('.cl-signIn-root').should('exist')
cy.get('input[name=identifier]').type(Cypress.env('test_user'))

cy.get('.cl-formButtonPrimary').contains('button', 'Continue').click()
cy.get('input[name=password]').type(Cypress.env('test_password'))

cy.get('.cl-formButtonPrimary').contains('button', 'Continue').click()
})

cy.url().should('include', '/protected')
// Ensure the user has successfully accessed the protected page
// by checking an element on the page that only the authenticated user can access
cy.contains('h1', 'This is a PROTECTED page')
})
})
```
2 changes: 1 addition & 1 deletion docs/testing/overview.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ To avoid sending an email or SMS message with a one time passcode (OTP) during t
Testing Tokens allow you to bypass bot detection mechanisms that protect Clerk applications from malicious bots, ensuring your test suites run smoothly. Without Testing Tokens, you may encounter "Bot traffic detected" errors in your requests.

> [!NOTE]
> While you can manually implement the following logic in your test suite, Clerk provides [Playwright](/docs/testing/playwright/overview) and [Cypress](/docs/testing/cypress) integrations that handle this automatically.
> While you can manually implement the following logic in your test suite, Clerk provides [Playwright](/docs/testing/playwright/overview) and [Cypress](/docs/testing/cypress/overview) integrations that handle this automatically.
Obtained via the [Backend API](/docs/reference/backend-api/tag/Testing-Tokens){{ target: '_blank' }}, Testing Tokens are short-lived and valid only for the specific instance for which they are issued.

Expand Down

0 comments on commit 54fb35b

Please sign in to comment.