Skip to content

Login Testing

Login flows deserve dedicated coverage: happy path, validation, error messages, and security redirects. These tests typically run without pre-seeded storageState.

Login Test Scenarios

Cover valid login redirect, invalid credentials error, empty field validation, and access to protected routes when unauthenticated.

Use role locators on the login form; mock auth API with route if backend unavailable in test env.

test.describe('Login', () => {
  test.use({ storageState: { cookies: [], origins: [] } }); // logged out

  test('redirects to dashboard on success', async ({ page }) => {
    await page.goto('/login');
    await page.getByLabel('Email').fill('user@example.com');
    await page.getByLabel('Password').fill('valid-pass');
    await page.getByRole('button', { name: 'Sign in' }).click();
    await expect(page).toHaveURL(/\/dashboard/);
  });
});

Empty storageState ensures logged-out starting point.

Cases to Cover

valid login → redirect
invalid password → error alert
empty email → field validation
logged-out user → /login redirect from /admin
  • Assert error messages with getByRole('alert').
  • Verify password field type=password not leaking.
  • Check returnUrl redirect after login if app supports it.
  • Rate limiting tests may need route mock or test hook.

Login Test Checklist

Standard login scenarios.

Case Assertion
Valid creds URL changes, welcome visible
Wrong password Error message visible
Empty submit Validation on fields
Logout Session cleared, protected 403
Deep link Return to intended URL post-login
Remember me Cookie persistence (optional)

Mocking Auth API

await page.route('**/api/login', route =>
  route.fulfill({ status: 401, body: '{"error":"invalid"}' })
);

Testing Invalid Login Paths

Assert error messages with await expect(page.getByRole('alert')).toContainText('Invalid') — keep happy-path login in one test, negative cases in separate tests.

Common Mistakes

  • Login tests using storageState — never hits login UI.
  • Not clearing cookies between login tests in same file.
  • Testing against real user passwords in repo.
  • Skipping negative cases — only happy path.

Key Takeaways

  • Login specs start logged out explicitly.
  • Cover success, failure, and validation paths.
  • Mock auth API when backend isolated.
  • Keep credentials in env vars.

Pro Tip

Parameterize email/password via env so the same tests run against staging test accounts without code changes.