Loading page...Загружаем страницу...正在加载页面...
AtlasRepo

How do you manage and inject browser cookies in Playwright to simulate pre-authenticated sessions or specific user state

Описание и применение

Тесты становятся быстрее и надёжнее, если вместо повторного входа через UI использовать сохранённый в Playwright состояние браузера, включая куки и localStorage.

Задача

Repetitive UI logins are test bottlenecks. They slow execution, introduce flakiness, and complicate test isolation.

Результат

Tests run faster, become more reliable, and maintain isolated sessions by skipping UI login and restoring full browser state.

Рабочий процесс

  • Perform login once and save the session state to a file using page.context().storageState({path:'playwright-auth.json'}) in a global setup test.
  • Configure subsequent tests to use the saved state by setting test.use({storageState:'playwright-auth.json'}) in playwright.config.ts or at the top of the test file.
  • Run tests that navigate directly to protected pages; the browser context is pre-authenticated with the saved cookies and localStorage.
  • Verify user-specific content to confirm the session is correctly restored.
  • Repeat as needed for different user states by creating separate storageState files.

Доказательства

Perform login once, then save the entire session state to a file. This can be done in a global setup test.

Источник

Use the saved storageState in new test contexts to start pre-authenticated, skipping the login UI.

Источник

Faster Tests: Skip UI login, significantly reducing test duration.

Источник

Increased Reliability: Eliminate flakiness often associated with login interactions.

Источник

  • Дата записи: 2026-10-20T12:56:16.561Z