Skip to main content

How to Write Browser Tests

Writing effective browser tests requires understanding asynchronous operations, element selection, and page navigation. This guide covers the essential patterns and techniques you need to know.

Asynchronous Operations

Most methods in the browser module return JavaScript promises, so k6 scripts must use the await keyword to wait for async operations to complete.

Basic Async Pattern

Why Use Async/Await?

The browser module uses asynchronous APIs for several reasons:
  1. JavaScript is single-threaded - async APIs prevent blocking the event loop
  2. Consistency with Playwright and other frontend testing frameworks
  3. Alignment with modern JavaScript development practices
If you forget await on asynchronous APIs, the script may finish before the test completes, resulting in errors like "Uncaught (in promise) TypeError: Object has no member 'goto'".

Handling Page Navigation

There are two recommended methods for handling page navigations: using Promise.all or using waitFor.

Using Promise.all

When actions trigger page navigation, use Promise.all to wait for both the action and navigation:
This prevents race conditions by ensuring the page is ready before continuing.

Wait for Specific Elements

Use locator.waitFor() to wait for important elements to appear:
This approach is often clearer than using Promise.all and makes scripts easier to follow.

Interacting with Elements

Use page.locator() to find elements and interact with them.

Finding Elements

Common Locator Methods

Selecting Elements

k6 browser supports CSS and XPath selectors. Choose selectors that are robust to DOM changes.
Best: User-facing attributes like ARIA labels and data attributes
Good: Text selectors using XPath
Use sparingly: IDs and class names
Avoid: Generic elements and absolute paths

Hybrid Testing Pattern

Combine browser tests with protocol-level tests using scenarios:

Benefits of Hybrid Testing

  • Test real user flows on the frontend while generating higher load in the backend
  • Measure backend and frontend performance in the same test execution
  • Increase collaboration between backend and frontend teams

Page Object Model

For large test suites, use the page object model pattern to improve maintainability:

Setting Thresholds

Set thresholds for browser metrics to define performance SLOs:

Next Steps

Best Practices

Learn optimization techniques and patterns

Overview

Review browser testing fundamentals