Stabilizing E2E Tests: Resolving CI Flakiness in Cronix with Playwright
Are your CI pipelines plagued by mysterious E2E test failures? The cronix project recently faced a similar challenge. Our continuous integration (CI) builds were often failing due to non-deterministic end-to-end (E2E) tests, leading to developer frustration and slower delivery cycles.
The Problem
Our E2E test suite, powered by Playwright, was frequently yielding different results in the CI environment compared to local runs. These 'flaky' tests would pass intermittently, making it difficult to trust the CI signal. Common culprits included:
- Timing Issues: Elements not being fully loaded or interactive when Playwright attempted to interact with them.
- State Management: Inconsistent application state between test runs, especially concerning user authentication or data setup.
- Environment Differences: Subtle variations in resource availability or network latency in the CI environment.
This unreliability directly impacted our development velocity, as developers spent valuable time re-running builds or manually verifying features that the tests should have covered.
The Approach
We embarked on a focused effort to stabilize our E2E suite, leveraging Playwright's robust features and adopting structured test patterns.
Phase 1: Pinpointing the Flakiness
The first step involved meticulously reviewing test logs and re-running failed tests locally multiple times. We identified patterns: certain tests failed more often, usually related to navigating complex forms, waiting for API responses, or asserting dynamic content.
Phase 2: Leveraging Playwright's Auto-Waits and Assertions
Playwright has excellent built-in auto-waiting mechanisms. However, sometimes explicit waits or more specific assertions are needed. We refined our element locators and added waitFor conditions where necessary to ensure elements were truly ready for interaction.
// Before: Prone to timing issues if button is not immediately enabled
await page.click('button#submit-form');
// After: Explicitly wait for button to be enabled before clicking
await page.locator('button#submit-form').click({ trial: true }); // Try clicking, Playwright retries until success or timeout
await expect(page.locator('button#submit-form')).toBeEnabled();
await page.click('button#submit-form');
This ensured that our tests waited for the UI to settle into a predictable state before proceeding.
Phase 3: Adopting Robust Test Patterns (Fixture Middleware)
A significant source of flakiness stemmed from inconsistent test setups, particularly around user authentication. To address this, we adopted a 'middleware-like' pattern using Playwright's custom test fixtures. This allowed us to encapsulate complex setup logic, ensuring every test started from a clean, authenticated state.
We defined a custom loggedInPage fixture that handles the login process once and provides an authenticated page object to subsequent tests. This streamlines tests and makes them highly repeatable.
// tests/fixtures/auth.ts
import { test as baseTest, expect } from '@playwright/test';
type MyFixtures = {
loggedInPage: any;
};
export const test = baseTest.extend<MyFixtures>({
loggedInPage: async ({ page }, use) => {
// Navigate to login and perform actions to authenticate
await page.goto('https://example.com/login');
await page.fill('input[name="username"]', 'testuser');
await page.fill('input[name="password"]', 'securepass');
await page.click('button[type="submit"]');
// Wait for navigation to a post-login page
await page.waitForURL('https://example.com/dashboard');
await expect(page.locator('h1')).toHaveText('Welcome, testuser!');
// Use this pre-authenticated page for the actual test
await use(page);
},
});
// Example usage in a test file:
// import { test } from '../fixtures/auth';
// test('should view user settings', async ({ loggedInPage }) => {
// await loggedInPage.goto('https://example.com/settings');
// await expect(loggedInPage.locator('h2')).toHaveText('Account Settings');
// });
This fixture acts as a middleware, preparing the testing environment reliably before each test executes, drastically reducing setup-related flakiness.
Final Numbers
| Metric | Before Fixes | After Fixes |
|---|---|---|
| CI E2E Success Rate | ~60% | >98% |
| CI Build Time (E2E) | Variable (retries) | Consistent |
| Developer Frustration | High | Low |
Key Insight
The most impactful change was establishing a consistent and robust test setup through custom Playwright fixtures. Treating these fixtures as a form of 'middleware' for test execution allowed us to abstract away flakiness-prone setup logic, making our tests faster, more reliable, and easier to maintain. Investing in robust test patterns like this pays dividends in developer confidence and CI stability.
Generated with Gitvlg.com