TL;DR
You will need to generate a valid session token and store it as cookies. This allows your E2E tests to access authenticated routes without manual login. This method works for both credentials-based and OAuth authentication.
GitHub Repo: nelsonlaidev/e2e-testing-with-better-auth
Preface
In this guide, we'll use Playwright as our E2E testing framework, but the concepts can be applied to other frameworks like Cypress.
For simplicity, we'll use a credentials-based authentication example. However, the same principles apply to OAuth providers.
Also, we use a SQLite database for demonstration purposes. Adjust the database interactions (e.g., table names, column types) according to your setup.
Generating a Session Token
To simulate an authenticated session, we'll need to generate a signed session token using BETTER_AUTH_SECRET
. This token will be used in session cookies.
Inserting Test Data
We want to keep our test user static to avoid creating multiple users during tests. Insert a test user, account, and session into the database if they don't already exist. We use 0
as the unique ID for all primary keys for simplicity.
Storing the Session
Save the signed token as a cookie in a JSON file for use in testing frameworks. Don't forget to encodeURIComponent
the cookie value.
Using the Session in Tests
Load the stored session in your E2E tests to access protected routes without logging in. The example below uses Playwright, but this can be adapted to any testing library (e.g., Cypress) that supports cookie injection.