Making E2E Tests Resilient: Tackling Auth and Dynamic UIs with Playwright
Flaky end-to-end (E2E) tests are a developer's nightmare. They erode trust in the test suite, slow down development cycles, and can hide actual bugs amidst a sea of false positives. In the ROMEROLUIS15/cronix project, we recently tackled common pain points in our E2E suite: tests failing due to inconsistent authentication states and dynamically hidden UI elements, particularly sidebar links.
The Challenge: Flaky E2E Tests
Our E2E test suite was suffering from intermittent failures that weren't indicative of actual application bugs. The two primary culprits were:
- Authentication Volatility: Tests would sometimes fail because a user wasn't properly logged in, or their session expired mid-test. This led to tests navigating to unexpected pages or failing permission checks.
- Dynamic UI Element Visibility: Our application's sidebar links, and other interactive elements, weren't always immediately visible or might be hidden based on user roles or loading states. Tests often attempted to click elements before they were interactable, leading to
element not foundorelement not visibleerrors.
These issues made the test suite unreliable, forcing manual re-runs and wasting valuable developer time.
Our Approach: Building Resilience
To combat flakiness, we focused on two key strategies using Playwright:
Persistent Authentication with storageState
Instead of logging in anew for every test, which is slow and prone to network issues, we implemented a global setup file to perform a single login and save the authentication state. Playwright's storageState feature allows us to capture the browser's local storage, session storage, and cookies after a successful login. Subsequent tests can then load this saved state, effectively starting with an authenticated session.
This dramatically speeds up tests and makes them more robust against temporary authentication server hiccups or network latency during login.
Robust Element Interaction with Explicit Waits
For dynamic UI elements, simply trying to click an element immediately after navigation is a recipe for flakiness. We adopted explicit waits using Playwright's locator.waitFor() and toBeVisible() assertions.
By waiting for an element to satisfy specific conditions (e.g., being visible, enabled, or attached to the DOM) before interacting with it, we ensure that our tests accurately reflect user behavior and are less sensitive to minor timing differences in page rendering.
Practical Example: Persistent Login and Element Waits
Here's a simplified example demonstrating how we implemented these strategies in TypeScript with Playwright.
First, a global setup for authentication (e.g., playwright.config.ts or a separate auth.setup.ts):
import { test as setup, expect } from '@playwright/test';
import path from 'path';
const authFile = path.join(__dirname, 'playwright/.auth/user.json');
setup('authenticate', async ({ page }) => {
await page.goto('https://example.com/login');
await page.locator('input[name="email"]').fill('[email protected]');
await page.locator('input[name="password"]').fill('your-secure-password');
await page.locator('button[type="submit"]').click();
// Wait until the dashboard is loaded, indicating successful login
await page.waitForURL('https://example.com/dashboard');
await expect(page.locator('.user-profile-widget')).toBeVisible();
await page.context().storageState({ path: authFile });
});
This setup file logs in and saves the session. Then, in our actual E2E tests, we configure Playwright to use this saved state:
// In playwright.config.ts
import path from 'path';
export default {
// ... other config
use: {
storageState: 'playwright/.auth/user.json',
},
// ... other config
projects: [
{
name: 'setup',
testMatch: /.*\.setup\.ts/,
},
{
name: 'chromium',
use: { ...devices['Desktop Chrome'], storageState: 'playwright/.auth/user.json' },
dependencies: ['setup'],
},
// ... other projects
],
};
And finally, a test that leverages the persistent login and waits for a dynamic sidebar link:
import { test, expect } from '@playwright/test';
test('should navigate to settings via sidebar', async ({ page }) => {
await page.goto('https://example.com/dashboard');
// Ensure the sidebar is visible, then wait for the specific link
const sidebarLink = page.locator('aside.sidebar a[href="/settings"]');
await sidebarLink.waitFor({ state: 'visible' });
await sidebarLink.click();
await page.waitForURL('https://example.com/settings');
await expect(page.locator('h1')).toHaveText('User Settings');
});
This approach ensures that our tests start from a known authenticated state and interact with the UI only when elements are truly ready.
Key Learnings & Best Practices
- Prioritize
storageState: For applications with authentication, usingstorageStateis a game-changer for test speed and reliability. It's often superior to programmatic API logins within each test. - Embrace Explicit Waits: Avoid relying on implicit waits or hardcoded
page.waitForTimeout(). Playwright'slocator.waitFor()and assertion matchers liketoBeVisible(),toBeEnabled(),toBeAttached()are your best friends for dealing with dynamic UIs. - Isolate Authentication: Keep your authentication flow in a dedicated setup file, separate from your core tests. This makes it easier to maintain and debug.
- Understand Application Loading States: Identify common loading indicators or UI states that signify when an element is ready for interaction.
Verdict
By systematically addressing authentication and dynamic UI element visibility, we significantly reduced flakiness in the cronix E2E test suite. Investing time in robust test patterns upfront pays dividends in developer confidence, faster feedback cycles, and ultimately, a more stable product.
Generated with Gitvlg.com