DEV Community

Styrow.dev
Styrow.dev

Posted on Originally published at styrow.dev

How do you efficiently manage `localStorage` for state setup and teardown in Playwright tests?

⚠️ 90% of Playwright tests waste precious seconds on UI setup!

Is your Playwright test suite bogged down by slow UI interactions just to get your app into a specific state? Learn how to instantly control localStorage for lightning-fast test execution.


📌 Problem Statement

Traditional Playwright tests often rely on navigating, clicking, and filling forms to achieve a desired application state (e.g., logged-in user, feature toggled). This approach is:

  • ❌ Slow: Each UI interaction adds latency.
  • ❌ Fragile: UI changes easily break selectors.
  • ❌ Inconsistent: External factors can influence intermediate states.

We need a way to directly inject application state, such as authentication tokens or feature flags, into localStorage to bypass these UI steps.

💡 Solution & Code Walkthrough

Playwright's page.evaluate() method is your secret weapon. It allows you to execute JavaScript directly within the browser context, giving you full control over window.localStorage. This is ideal for pre-setting application state in test.beforeEach.

import { test } from '@playwright/test';

test.beforeEach(async ({ page }) => {
  await page.goto('http://localhost:3000'); // Navigate to your app's base URL

  // ✅ Directly inject application state into localStorage
  await page.evaluate(() => {
    localStorage.setItem('userLoggedIn', 'true'); // Simulate a logged-in session
    localStorage.setItem('featureToggleA', 'enabled'); // Activate a specific feature
    localStorage.setItem('userConfig', JSON.stringify({ theme: 'dark', notifications: true }));
  });

  // • Optional: Verify the state was set (helpful for debugging)
  // const isLoggedIn = await page.evaluate(() => localStorage.getItem('userLoggedIn'));
  // console.log('User logged in state:', isLoggedIn);
});

test('should display content for logged-in user', async ({ page }) => {
  // Now, your test starts with the user already logged in!
  await page.locator('#loggedInContent').waitFor({ state: 'visible' });
  // ... proceed with tests assuming the desired state
});
Enter fullscreen mode Exit fullscreen mode

• How it works:

  • test.beforeEach: Ensures localStorage is set before each test runs.
  • page.goto(): Navigate to your application. localStorage can only be set for the origin you are currently on.
  • page.evaluate(): Executes the provided JavaScript function in the browser.
  • localStorage.setItem(key, value): Standard browser API to store data.
  • JSON.stringify(): Essential for storing complex objects; localStorage only stores strings.

🔑 Key Takeaways

  • ✅ Use page.evaluate() for direct localStorage manipulation.
  • ✅ Set up state in test.beforeEach for consistent test starting points.
  • ✅ Stringify complex objects (e.g., JSON) before storing them in localStorage.
  • ❌ Avoid slow UI interactions for state setup whenever possible.
  • • This method drastically improves test speed and reliability.

❓ Quick Summary Q&A

  • Q: Why use page.evaluate() for localStorage?
    • A: It executes JavaScript in the browser context, granting direct access to window.localStorage.
  • Q: Where should localStorage setup code go?
    • A: In test.beforeEach to ensure consistent state for each test.
  • Q: Can I store objects in localStorage?
    • A: Yes, but you must JSON.stringify() them before setting and JSON.parse() when retrieving.

TAGS: playwright, typescript, testing, automation, e2e, localStorage, frontend
────────────────────────────────────────
Supercharge your testing skills!
────────────────────────────────────────

📲 𝐅𝐑𝐄𝐄 𝐌𝐎𝐁𝐈𝐋𝐄 𝐀𝐏𝐏 — 𝟔𝟎𝟎+ 𝐒𝐃𝐄𝐓 𝐐&𝐀𝐬
Practice real-world interview scenarios offline on the free QA Automation & SDET Prep app:

🤖 𝐆𝐨𝐨𝐠𝐥𝐞 𝐏𝐥𝐚𝐲 (𝐀𝐧𝐝𝐫𝐨𝐢𝐝):
https://play.google.com/store/apps/details?id=com.app.seleniuminterviewquestions&referrer=utm_source%3Ddevto%26utm_medium%3Darticle%26utm_campaign%3Dselenium_20261112

🍎 𝐀𝐩𝐩 𝐒𝐭𝐨𝐫𝐞 (𝐢𝐎𝐒):
https://apps.apple.com/app/id6786760948?pt=128640464&ct=devto_selenium_20261112&mt=8

────────────────────────────────────────
────────────────────────────────────────

Top comments (0)