Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 35 ยท Network and Data

Test Data and Logging In Fast

Seed and reset test data through APIs, skip repeated UI logins with cy.session and Playwright storageState, and keep test secrets out of your repository.

Every non-trivial end-to-end test needs two things before it starts: the right data (a product to buy, an existing account) and the right identity (a logged-in user). The slow, fragile way is to build both through the user interface at the start of every test: open the login page, type credentials, click, wait, create the product by filling a form, and only then begin the test you actually care about. Multiply that by 200 tests and your suite crawls, and a bug in the login form makes all 200 fail at once.

The professional approach is to prepare data and identity behind the scenes, through an API or a database script, and use the UI only for the thing the test is actually about. In this lesson you will learn how to seed and reset data, how cy.session and Playwright's storageState reuse a login, and how to keep passwords and tokens out of your code. Networking basics are in Intercepting and Mocking Network Requests; the next lesson, Testing APIs Directly, covers the request APIs used here.

The real tools, a real server and a browser cannot run on this site, so the Cypress and Playwright code is read-only. The runnable examples are stand-ins: a fake auth server and a fake database in plain JavaScript that reproduce the logic (counting logins, caching a session, avoiding data collisions). They are not the tools' code.

Why logging in through the UI every time hurts

Logging in is a flow you should test once or twice thoroughly (see Project: Test a Login Flow). Every other test just needs to be logged in. If each test types credentials into the form, you pay three costs:

  • Time. A UI login takes seconds. An API login takes a fraction of a second. Reusing a saved session takes almost nothing.
  • Fragility. A failure in the login page breaks every test, hiding the real problems.
  • Noise. Your test reports fill with repeated steps that have nothing to do with the feature under test.
flowchart LR
  subgraph slow["UI login in every test"]
    A1["Test 1: open page, type, click"] --> A2["Test 2: open page, type, click"] --> A3["Test 3: open page, type, click"]
  end
  subgraph fast["Saved session"]
    B0["Log in once (API)"] --> B1["Test 1 starts logged in"]
    B0 --> B2["Test 2 starts logged in"]
    B0 --> B3["Test 3 starts logged in"]
  end

Log in once, reuse the saved cookies and storage in every test.

Reusing a session in Cypress

cy.session(id, setup, options) runs your setup function the first time, saves the cookies, local storage and session storage, and on later calls with the same id restores them instead of running setup again. Wrap it in a custom command so every test can call it:

JavaScript
// Cypress (read-only): cypress/support/commands.js
Cypress.Commands.add('login', (email, password) => {
  cy.session(
    [email],                                   // the session id
    () => {
      cy.request('POST', '/api/login', { email, password }).then(({ body }) => {
        window.localStorage.setItem('token', body.token)
      })
    },
    {
      validate() {                             // is the saved session still good?
        cy.request('/api/me').its('status').should('eq', 200)
      },
    }
  )
})

// in a spec
beforeEach(() => {
  cy.login('[email protected]', Cypress.env('USER_PASSWORD'))
  cy.visit('/dashboard')                       // cy.session leaves a blank page: visit afterwards
})

Notes you should know:

  • The validate function checks that the saved session still works (tokens expire). If validation fails, Cypress runs setup again automatically.
  • cy.session clears the page, cookies and storage before setup and starts each test from the restored state. You still have to cy.visit() afterwards.
  • Sessions are kept for the whole run, shared by the tests of a spec. There is an option to share them across specs; check the docs of your Cypress version before relying on it.

Keep the session id specific. If two different users share one id, they share one login.

Reusing a session in Playwright

Playwright saves the browser state to a JSON file called storage state. A common pattern is a "setup" project that logs in once, writes the file, and other projects that depend on it and load it:

TypeScript
// Playwright (read-only): playwright.config.ts
import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  use: { baseURL: process.env.BASE_URL ?? 'http://localhost:3000' },
  projects: [
    { name: 'setup', testMatch: /auth\.setup\.ts/ },
    {
      name: 'chromium',
      use: { ...devices['Desktop Chrome'], storageState: 'playwright/.auth/user.json' },
      dependencies: ['setup'],               // runs after the setup project
    },
  ],
});
TypeScript
// Playwright (read-only): tests/auth.setup.ts
import { test as setup, expect } from '@playwright/test';

const authFile = 'playwright/.auth/user.json';

setup('log in once', async ({ request }) => {
  const response = await request.post('/api/login', {
    data: { email: '[email protected]', password: process.env.USER_PASSWORD },
  });
  expect(response.ok()).toBeTruthy();
  await request.storageState({ path: authFile });   // save cookies for the other tests
});

Every test in the chromium project then starts with the user already signed in, with no setup code in the test itself. Add playwright/.auth/ to .gitignore: the file contains live session data. If your app stores its token in localStorage rather than cookies, log in through the page once in the setup file and save with page.context().storageState({ path: authFile }), which includes local storage. There is also the older globalSetup option (a function that runs once before all tests); the setup project is usually better because it appears in reports and traces. Configuration and Environments shows more about projects.

A session cache stand-in

The stand-in below compares three strategies over 12 tests on a virtual clock: logging in through the UI each time (3 seconds), logging in through the API each time (0.2 seconds), and a cy.session style cache that validates the saved token (0.02 seconds) and logs in again only if the server says it is expired. Each test body is 1.5 seconds. The fake tokens last 10 virtual seconds, so the cached session has to refresh once.

JS A session cache versus logging in every time

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Twelve UI logins cost 54.0 seconds, twelve API logins 20.4 seconds, and the cached session 18.6 seconds with only two logins: the first one, and one refresh when the validation step discovered the token had expired. The real tools do the same dance with real cookies and a real clock. Without the validation step, the second half of the suite would run with an expired token and fail in confusing ways.

Seeding and resetting data

Data has the same problem: building it through forms is slow, and leftovers from one test confuse the next. There are three common ways to prepare it, from most to least preferred:

  1. API calls. The test calls your backend's own endpoints (POST /api/products) to create exactly what it needs. This is fast and uses code paths your app already has.
  2. A test-only reset or seed endpoint or a command-line script, for example POST /test-api/reset or php artisan migrate:fresh --seed, for bulk setup. Such endpoints must exist only in test and development environments.
  3. Direct database access from the test process. Cypress runs Node code through cy.task() (the browser code cannot talk to a database); Playwright tests already run in Node and can import your database helper.
JavaScript
// Cypress (read-only)
beforeEach(() => {
  cy.request('POST', '/test-api/reset')                      // known empty state
  cy.request('POST', '/api/products', { name: 'Desk lamp', price: 30 })
  cy.task('db:seed', { users: 3 })                            // runs Node code, configured in cypress.config.js
})
TypeScript
// Playwright (read-only): a fixture that creates and removes its own data
import { test as base } from '@playwright/test';

export const test = base.extend<{ product: { id: number; name: string } }>({
  product: async ({ request }, use) => {
    const response = await request.post('/api/products', { data: { name: 'Desk lamp ' + Date.now(), price: 30 } });
    const product = await response.json();
    await use(product);                                   // the test runs here
    await request.delete('/api/products/' + product.id); // cleanup afterwards
  },
});

Fixtures like this are covered in Hooks, Fixtures and Custom Commands. Two rules keep data from causing flaky tests: every test creates what it needs and names must be unique when tests can run in parallel.

JS Unique data versus a fixed record

Press Run (or Ctrl + Enter) to see the console output here.

No output.

With one fixed email the second test fails because the first one already took it. With unique emails both pass, but two rows are left behind, which is why you also need a cleanup (a fixture teardown, an afterEach, or a reset before the next run).

Handling secrets

Tests need credentials, and credentials do not belong in your repository.

  • Read them from environment variables: process.env.USER_PASSWORD in Playwright, Cypress.env('USER_PASSWORD') in Cypress (Cypress picks up variables that start with CYPRESS_, such as CYPRESS_USER_PASSWORD).
  • Locally use an untracked file (for example .env or cypress.env.json) listed in .gitignore. In CI use the pipeline's secret store (see Running Tests in CI).
  • Use dedicated test accounts with the least permissions needed, on test or staging systems. Never run automated tests with a real person's account or with production admin credentials.
  • Do not print tokens in logs, and do not commit saved session files such as playwright/.auth/user.json.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is it better to log in through an API call than through the login form in most tests?

    Login should be tested thoroughly in a few dedicated tests. Elsewhere, an API login or a saved session saves time and keeps failures focused.
  2. 2. What is the job of the validate option in cy.session?

    Sessions can expire. The validate function lets Cypress notice and rebuild the session automatically.
  3. 3. How do other Playwright projects reuse the login done in a setup project?

    The setup project writes cookies and storage to a JSON file; dependent projects start each test with that state.
  4. 4. Two tests running in parallel both create a user with the email [email protected] and one of them fails. What is the best fix?

    Unique data removes the collision at its source. Sleeps and single workers hide the problem and slow the suite.
  5. 5. Where should the password for a test account live?

    Secrets stay out of the repository. Read them from the environment and use dedicated low-privilege test accounts.

Summary

  • Prepare identity and data behind the scenes; use the UI for the feature under test.
  • Cypress: cy.session(id, setup, { validate }), usually wrapped in a custom login command, then cy.visit().
  • Playwright: a setup project writes storageState to a file; other projects load it and depend on the setup project.
  • Seed data through API calls, test-only endpoints or scripts, and use unique values plus cleanup so parallel tests never collide.
  • Keep secrets in environment variables or CI secret stores, and never commit saved session files.
  • The stand-ins show the logic with virtual time and fake servers; the real tools use real cookies, storage and clocks.

Next: Testing APIs Directly