Managing and Asserting Complex Page State in Playwright
说明与用途
在 Playwright 中,序列化复杂对象,使用 page.evaluate 注入到 localStorage,然后检索并断言其结构,以确保测试隔离。
问题
Testing UIs that rely on dynamic, custom-structured local storage data or intricate session objects makes standard Playwright state persistence insufficient, breaking test repeatability and isolation.
结果
By injecting complex state via page.evaluate, tests achieve strong isolation and can assert deeply nested structures without relying on fragile UI selectors.
工作流
- 1. Define a complex JavaScript object representing the desired app state.
- 2. Use
await page.evaluate((state)=>{localStorage.setItem('appData', JSON.stringify(state));}, complexState)before navigating to the page. - 3. Navigate to the target page with
await page.goto('/dashboard'). - 4. (Optional) Interact with the UI as needed.
- 5. Retrieve the stored state with
const retrieved = await page.evaluate(()=>JSON.parse(localStorage.getItem('appData')||'{}')); - 6. Assert the nested structure using Playwright's
expectAPI.
证据
Use await page.evaluate((state)=>{localStorage.setItem('appData', JSON.stringify(state));}, complexState) before navigating to the page.
- 记录日期: 2026-09-22T12:15:43.118Z