Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 35 ยท Projects

Project: Test a Login Flow

Build a complete test plan for a login page in Cypress and Playwright: valid and invalid logins, validation, redirects and fast session reuse, side by side.

Login is the first thing almost every application asks of its users, and the first thing that stops every other test if it breaks. It is also a perfect practice project: it has a happy path, several failure paths, input validation, a redirect, and a performance problem (logging in through the form before every test is slow). In this project you will plan the tests, write them in both Cypress and Playwright, and see how session reuse removes the repeated login.

The real tools and a real web server cannot run on this site, so the Cypress and Playwright tests are read-only. The runnable parts are stand-ins: a small login application written as a plain JavaScript object, and a test runner that drives it with the same kinds of steps (fill, click, assert). The stand-in tests prove the test plan is sound; the read-only code shows how you would write it for a real browser.

The behavior to test

Our imaginary login page has these rules. Writing them down first is the most valuable step of any test project, because each rule becomes one or more tests.

# Rule Test
1 Valid email and password sign the user in and open /dashboard happy path
2 An empty email shows "Email is required" and does not call the server validation
3 An email without @ shows "Enter a valid email" validation
4 An empty password shows "Password is required" validation
5 A wrong password shows "Incorrect email or password" failure path
6 An unknown email shows the same message as a wrong password security
7 Visiting /dashboard while signed out redirects to /login redirect
8 After the redirect, a successful login returns to the page the user wanted redirect
9 A malicious next address (another site) is ignored security
10 A signed-in user who visits /login goes straight to /dashboard redirect

Rule 6 deserves a comment: if the page says "No such user" for unknown emails and "Wrong password" for known ones, an attacker can discover which emails have accounts. One message for both closes that leak, and a test keeps it closed.

flowchart TD
  A["Visit /dashboard"] --> B{"Signed in?"}
  B -->|"yes"| C["Show dashboard"]
  B -->|"no"| D["Redirect to /login?next=/dashboard"]
  D --> E["Submit the form"]
  E --> F{"Valid input?"}
  F -->|"no"| G["Show field errors,<br/>no request sent"]
  F -->|"yes"| H{"Credentials correct?"}
  H -->|"no"| I["Show generic error"]
  H -->|"yes"| J["Create session,<br/>go to next or /dashboard"]

Every box that has two exits needs at least one test per exit.

The stand-in application

Before the real test code, here is the application as plain JavaScript. It keeps its own state (path, errors, session) and exposes the actions a user has: visit a URL, fill a field, press the button. Run it and read the printed "screens", which are what a user would see after each step.

JS The login application (stand-in)

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

No output.

The output shows the redirect (signed out visit to /dashboard ends on /login), the validation messages, the generic wrong-password message, and the jump back to /dashboard after success because the redirect remembered next. A real app does all this across browser, network and server, but the rules are the same, and so are the tests.

The tests in Cypress

Give the form elements stable data-cy attributes (see Writing Selectors That Do Not Break). Then rules 1 to 5 look like this:

JavaScript
// cypress/e2e/login.cy.js (read-only)
describe('login', () => {
  beforeEach(() => {
    cy.visit('/login')
  })

  it('signs in with valid credentials (rule 1)', () => {
    cy.get('[data-cy=email]').type('[email protected]')
    cy.get('[data-cy=password]').type(Cypress.env('PASSWORD'), { log: false })
    cy.contains('button', 'Sign in').click()

    cy.location('pathname').should('eq', '/dashboard')
    cy.contains('h1', 'Welcome back').should('be.visible')
  })

  it('requires an email (rule 2)', () => {
    cy.get('[data-cy=password]').type('anything')
    cy.contains('button', 'Sign in').click()
    cy.get('[data-cy=email-error]').should('have.text', 'Email is required')
    cy.location('pathname').should('eq', '/login')
  })

  it('shows one generic message for wrong password and unknown user (rules 5 and 6)', () => {
    const attempts = [
      ['[email protected]', 'wrong-password'],
      ['[email protected]', 'wrong-password'],
    ]
    attempts.forEach(([email, password]) => {
      cy.get('[data-cy=email]').clear().type(email)
      cy.get('[data-cy=password]').clear().type(password, { log: false })
      cy.contains('button', 'Sign in').click()
      cy.get('[role=alert]').should('have.text', 'Incorrect email or password')
    })
  })

  it('returns to the wanted page after login (rule 8)', () => {
    cy.visit('/dashboard')
    cy.location('pathname').should('eq', '/login')
    cy.get('[data-cy=email]').type('[email protected]')
    cy.get('[data-cy=password]').type(Cypress.env('PASSWORD'), { log: false })
    cy.contains('button', 'Sign in').click()
    cy.location('pathname').should('eq', '/dashboard')
  })
})

Two details matter. { log: false } keeps the typed password out of the command log and screenshots. And the assertions on cy.location('pathname') retry (see Assertions That Retry), so the test waits for the redirect instead of sleeping.

The same tests in Playwright

TypeScript
// tests/login.spec.ts (read-only)
import { test, expect } from '@playwright/test';

test.describe('login', () => {
  test.beforeEach(async ({ page }) => {
    await page.goto('/login');
  });

  test('signs in with valid credentials (rule 1)', async ({ page }) => {
    await page.getByLabel('Email').fill('[email protected]');
    await page.getByLabel('Password').fill(process.env.TEST_PASSWORD!);
    await page.getByRole('button', { name: 'Sign in' }).click();

    await expect(page).toHaveURL('/dashboard');
    await expect(page.getByRole('heading', { name: /welcome back/i })).toBeVisible();
  });

  test('requires an email (rule 2)', async ({ page }) => {
    await page.getByLabel('Password').fill('anything');
    await page.getByRole('button', { name: 'Sign in' }).click();
    await expect(page.getByText('Email is required')).toBeVisible();
    await expect(page).toHaveURL('/login');
  });

  for (const [email, label] of [
    ['[email protected]', 'wrong password'],
    ['[email protected]', 'unknown user'],
  ]) {
    test(`shows a generic message for ${label} (rules 5 and 6)`, async ({ page }) => {
      await page.getByLabel('Email').fill(email);
      await page.getByLabel('Password').fill('wrong-password');
      await page.getByRole('button', { name: 'Sign in' }).click();
      await expect(page.getByRole('alert')).toHaveText('Incorrect email or password');
    });
  }

  test('returns to the wanted page after login (rule 8)', async ({ page }) => {
    await page.goto('/dashboard');
    await expect(page).toHaveURL(/\/login/);
    await page.getByLabel('Email').fill('[email protected]');
    await page.getByLabel('Password').fill(process.env.TEST_PASSWORD!);
    await page.getByRole('button', { name: 'Sign in' }).click();
    await expect(page).toHaveURL('/dashboard');
  });
});

Playwright can generate one test per data row with a plain for loop, which keeps rules 5 and 6 as separate named tests in the report. In Cypress, you can do the same with forEach around it(...); our version put both attempts into one test for brevity. The first approach gives clearer failure messages.

Compare the two styles: Cypress commands chain and retry implicitly; Playwright awaits each step and retries inside expect. Both find the elements by what a user sees or by a stable attribute, and neither uses fixed sleeps.

Reusing a session

There is a catch in the tests above. Every test that is not about login but needs a signed-in user would repeat the form steps, which costs seconds each time and makes login failures break unrelated tests. The fix: log in once, save the session, and reuse it. Only the login tests themselves go through the form.

In Cypress, cy.session caches cookies and storage under a name:

JavaScript
// cypress/support/commands.js (read-only)
Cypress.Commands.add('loginAs', (email, password) => {
  cy.session(
    [email],                          // the cache key
    () => {                           // runs only when no cached session exists
      cy.visit('/login')
      cy.get('[data-cy=email]').type(email)
      cy.get('[data-cy=password]').type(password, { log: false })
      cy.contains('button', 'Sign in').click()
      cy.location('pathname').should('eq', '/dashboard')
    },
    {
      validate() {                    // is the cached session still good?
        cy.request('/api/me').its('status').should('eq', 200)
      },
    }
  )
})

// in a spec
beforeEach(() => {
  cy.loginAs('[email protected]', Cypress.env('PASSWORD'))
  cy.visit('/dashboard')
})

In Playwright, a setup project logs in once and saves the browser state to a file; other projects load it:

TypeScript
// tests/auth.setup.ts (read-only)
import { test as setup, expect } from '@playwright/test';

setup('sign in once', async ({ page }) => {
  await page.goto('/login');
  await page.getByLabel('Email').fill('[email protected]');
  await page.getByLabel('Password').fill(process.env.TEST_PASSWORD!);
  await page.getByRole('button', { name: 'Sign in' }).click();
  await expect(page).toHaveURL('/dashboard');
  await page.context().storageState({ path: 'playwright/.auth/user.json' });
});
TypeScript
// playwright.config.ts (read-only, projects only)
projects: [
  { name: 'setup', testMatch: /.*\.setup\.ts/ },
  {
    name: 'chromium',
    use: { storageState: 'playwright/.auth/user.json' },
    dependencies: ['setup'],
  },
],

The login spec itself must start signed out, so it overrides the saved state with test.use({ storageState: { cookies: [], origins: [] } }). Remember to keep the saved file out of version control, because it holds a live session. The idea is explained in Test Data and Logging In Fast.

Running the plan against the stand-in

The last runnable example is the whole test plan: all ten rules as tests, plus a session cache that counts how many real logins happen. It reuses a compact copy of the application so the example is self-contained.

JS The full test plan, with session reuse

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

No output.

The last two lines are the payoff. Three tests needed a signed-in user and used zero additional form logins, because test 10 had already filled the cache. In a real suite with 200 tests, that is 200 fewer trips through the form. Notice also that the tests which exercise the form (1 to 9) each create a fresh app, so none can influence another.

Extending the project

Try adding these rules to the test plan, in both tools if you can:

  • A "Show password" toggle changes the input type; assert on the attribute, not on pixels.
  • After five failed attempts the page shows a lockout message (stub the server response with the techniques of Intercepting and Mocking Network Requests).
  • Logging out clears the session and /dashboard redirects again.
  • The form is usable by keyboard only: tab to the fields, press Enter to submit.
  • Add an axe scan of the login page (see Visual and Accessibility Testing).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should the wrong-password and unknown-user cases show the same message?

    Separate messages let an attacker discover registered emails. A test with the same expected text for both cases keeps that protection from regressing.
  2. 2. What does cy.session (or Playwright's storageState) mainly buy you?

    The session is created once and restored for later tests, which saves time and keeps unrelated tests from failing when the login UI breaks.
  3. 3. Why do the login tests themselves still use the real form?

    Reusing a session skips the form. For tests about the form, skipping it would test nothing.
  4. 4. A signed-out user opens /dashboard, signs in, and should end up back on /dashboard. What is the most reliable way to assert the redirect?

    Retrying URL assertions wait exactly as long as needed and fail with a clear message if the redirect never happens.

Summary

  • Start from a written list of rules; each rule with two outcomes needs a test per outcome.
  • Cover the happy path, validation, failure paths, redirects and the security rules (generic error message, safe next handling).
  • Use stable selectors, retrying assertions on the URL and messages, and { log: false } or environment variables for secrets.
  • Log in through the form only in the tests about login; reuse a session (cy.session, storageState) everywhere else.
  • Keep every test independent so the suite can run in parallel.

Next: Project: Test a Todo App