⚠️ 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
});
• How it works:
-
test.beforeEach: EnsureslocalStorageis set before each test runs. -
page.goto(): Navigate to your application.localStoragecan 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;localStorageonly stores strings.
🔑 Key Takeaways
- ✅ Use
page.evaluate()for directlocalStoragemanipulation. - ✅ Set up state in
test.beforeEachfor 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()forlocalStorage?- A: It executes JavaScript in the browser context, granting direct access to
window.localStorage.
- A: It executes JavaScript in the browser context, granting direct access to
- Q: Where should
localStoragesetup code go?- A: In
test.beforeEachto ensure consistent state for each test.
- A: In
- Q: Can I store objects in
localStorage?- A: Yes, but you must
JSON.stringify()them before setting andJSON.parse()when retrieving.
- A: Yes, but you must
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)