Managing and Asserting Complex Page State in Playwright
Описание и применение
В Playwright можно сериализовать сложные объекты, вставить их в localStorage через page.evaluate, затем проверить их наличие и структуру, обеспечивая изоляцию тестов.
Задача
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