Test authenticated flows
Playwright executes tests in isolated environments called browser contexts. Because each test case runs in a new browser context, the user session is not shared between test cases by default. However, tests can load existing authenticated state.
This guide demonstrates how to save the auth state globally and load it in your test cases, eliminating the need to authenticate in every test and speeding up test execution. Visit the Playwright docs about authentication for more information.
Create a storage directory
Create a playwright/.clerk
directory and add it to your .gitignore
. Once the auth state is generated, it will be stored to a file in this directory. Later on, tests will reuse this state and start already authenticated.
Prepare auth state for your tests
Authenticate and save the auth state in your global setup file.
This file:
- Is executed before all projects.
- Calls
clerkSetup()
to configure Playwright with Clerk. - Calls
clerk.signIn()
to sign in a test user using credentials stored in environment variables. See the reference for more information about the different parameters you can pass. - Checks if the user can access a protected page to ensure the user is successfully authenticated.
- Stores the auth state in the storage file.
Load the stored auth state in your tests
You can either load the stored auth state in the config or directly in a test file. Loading in the config is useful if you want to authenticate once and reuse the same auth state for all tests or groups of tests. Loading in a test file is useful if you want to authenticate for a specific test case.
In the config
In your playwright.config.ts
, create a global setup
project and declare it as a dependency for all your testing projects. This means that the global setup
project will always run before all the tests, and because it's where you prepared auth state, it will authenticate before all the tests. All testing projects should use the authenticated state as storageState
.
In a test file
To use the stored auth state in a test file, see the following example:
For more information, feedback, or issues, visit the @clerk/testing
package.
Feedback
Last updated on