How do you manage and inject browser cookies in Playwright to simulate pre-authenticated sessions or specific user state
说明与用途
通过使用 Playwright 的 storageState 跳过 UI 登录并恢复完整的浏览器会话数据,测试速度更快、可靠性更高。
问题
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