🔥 Playwright Pro-Tip: Are your E2E tests missing crucial browser environment validation? Modern web apps dynamically adapt to user agents, platforms, and custom flags, often leading to subtle bugs.
📌 Problem Statement
Web applications frequently alter behavior based on browser environment (e.g., navigator.userAgent, navigator.platform, custom JS globals).
❌ Manually testing these permutations is tedious and error-prone.
• The challenge: Validate application behavior across diverse environments within a single, robust E2E test run.
💡 Solution & Code Walkthrough
Leverage Playwright's browser.newContext() for isolation and context.addInitScript() to inject JavaScript, dynamically modifying browser globals before app scripts execute. This strategy allows parameterized tests to iterate through different configurations.
// env.test.ts
import { test, expect } from '@playwright/test';
const envConfigs = [
{ name: 'Desktop-Chrome', userAgent: 'Chrome UA', platform: 'Win32', featureFlag: true },
{ name: 'Mobile-Safari', userAgent: 'Safari UA', platform: 'iPhone', featureFlag: false }
];
for (const config of envConfigs) {
test(`Validates app behavior for ${config.name}`, async ({ browser }) => {
// 1. Create isolated browser context with desired userAgent header
const context = await browser.newContext({ userAgent: config.userAgent });
// 2. Inject script to modify JS globals *before* app loads
await context.addInitScript((_cfg) => {
// Override navigator properties for JS
Object.defineProperty(navigator, 'userAgent', { get: () => _cfg.userAgent });
Object.defineProperty(navigator, 'platform', { get: () => _cfg.platform });
// Inject custom global variable
(window as any)._APP_FEATURE_X_ = _cfg.featureFlag;
}, config); // Pass config data to init script
const page = await context.newPage();
await page.goto('https://example.com'); // Your application URL
// 3. Verify modifications took effect in page context
expect(await page.evaluate(() => navigator.userAgent)).toBe(config.userAgent);
expect(await page.evaluate(() => navigator.platform)).toBe(config.platform);
expect(await page.evaluate(() => (window as any)._APP_FEATURE_X_)).toBe(config.featureFlag);
// Add application-specific assertions here based on expected UI/logic
await context.close();
});
}
🔑 Key Takeaways
✅ newContext(): Ensures isolated test runs for each environment configuration.
✅ addInitScript(): Crucial for modifying browser's navigator properties and injecting custom globals before application scripts execute.
✅ Parameterization: Iterate through environment configurations for comprehensive coverage.
• Real-world fidelity: Mimic diverse user scenarios and prevent environment-specific regressions.
❓ Quick Summary Q&A
Q: Why addInitScript instead of page.evaluate?
A: addInitScript runs before any page scripts, allowing modification of browser globals that the app might read on load. page.evaluate runs after the page is loaded.
Q: How to set HTTP User-Agent header?
A: Pass the userAgent option directly to browser.newContext().
Q: Does this clear cookies between runs?
A: Yes, browser.newContext() ensures a fresh, isolated session for each test run.
TAGS: playwright, e2e testing, browser automation, javascript, quality assurance, devops, web development
────────────────────────────────────────
Ready to master Playwright & ship flawless code? Download our app for more advanced tutorials and challenges!
────────────────────────────────────────
📲 𝐅𝐑𝐄𝐄 𝐌𝐎𝐁𝐈𝐋𝐄 𝐀𝐏𝐏 — 𝟔𝟎𝟎+ 𝐒𝐃𝐄𝐓 𝐐&𝐀𝐬
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_20261130
🍎 𝐀𝐩𝐩 𝐒𝐭𝐨𝐫𝐞 (𝐢𝐎𝐒):
https://apps.apple.com/app/id6786760948?pt=128640464&ct=devto_selenium_20261130&mt=8
────────────────────────────────────────
────────────────────────────────────────
Top comments (0)