No results for

Powered byAlgolia

Running browser tests

Follow along to learn how to:

  1. Run a test
  2. Interact with elements on your webpage
  3. Wait for page navigation
  4. Run both browser-level and protocol-level tests in a single script
note

With these example snippets, you'll run the test locally with your machine's resources. The browser module is not available within k6 cloud as of yet.

Run a test

To run a simple local script:

  1. Copy the following code, paste it into your favorite editor, and save it as script.js:

Note that providing an executor and setting the browser scenario option's type to chromium is mandatory. Please see the options and scenarios documentation for more information.

script.js
1import { browser } from 'k6/experimental/browser';
2
3export const options = {
4 scenarios: {
5 ui: {
6 executor: 'shared-iterations',
7 options: {
8 browser: {
9 type: 'chromium',
10 },
11 },
12 },
13 },
14}
15
16export default async function () {
17 const page = browser.newPage();
18
19 try {
20 await page.goto('https://test.k6.io/');
21 page.screenshot({ path: 'screenshots/screenshot.png' });
22 } finally {
23 page.close();
24 }
25}

The preceding code imports the browser (the browser module), and uses its newPage method to open a new page.

After getting the page, you can interact with it using the Page methods. This example visits a test URL and takes a screenshot of the page.

Subsequently, the page is closed. This allows for the freeing up of allocated resources and enables the accurate calculation of Web Vital metrics.

note

To provide rough compatibility with the Playwright API, the browser module API is also being converted from synchronous to asynchronous. page.goto() is now asynchronous so await keyword is used to deal with the asynchronous nature of the operation.

  1. Then, run the test on your terminal with this command:
Bash
Docker
Windows: CMD
Windows: PowerShell
$ k6 run script.js

You can also use the browser module options to customize the launching of a browser process. For instance, you can start a headful browser using the previous test script with this command.

Bash
Docker
Windows: CMD
Windows: PowerShell
$ K6_BROWSER_HEADLESS=false k6 run script.js
note

When using Docker to run k6 browser tests, make sure you have pulled the correct image with Chromium built-in. See k6 Installation via Docker for more information.

Interact with elements on your webpage

You can use page.locator() and pass in the element's selector you want to find on the page. page.locator() will create and return a Locator object, which you can later use to interact with the element.

To find out which selectors the browser module supports, check out Selecting Elements.

note

You can also use page.$() instead of page.locator(). You can find the differences between page.locator() and page.$ in the Locator API documentation.

script.js
1import { browser } from 'k6/experimental/browser';
2
3export const options = {
4 scenarios: {
5 ui: {
6 executor: 'shared-iterations',
7 options: {
8 browser: {
9 type: 'chromium',
10 },
11 },
12 },
13 },
14}
15
16export default async function () {
17 const page = browser.newPage();
18
19 try {
20 await page.goto('https://test.k6.io/my_messages.php');
21
22 // Enter login credentials
23 page.locator('input[name="login"]').type('admin');
24 page.locator('input[name="password"]').type('123');
25
26 page.screenshot({ path: 'screenshots/screenshot.png' });
27 } finally {
28 page.close();
29 }
30}

The preceding code creates and returns a Locator object with the selectors for both login and password passed as arguments.

Within the Locator API, various methods such as type() can be used to interact with the elements. The type() method types a text to an input field.

Asynchronous operations

Since many browser operations happen asynchronously, and to follow the Playwright API more closely, we are working on migrating most of the browser module methods to be asynchronous as well.

At the moment, methods such as page.goto(), page.waitForNavigation() and Element.click() return JavaScript promises, and scripts must be written to handle this properly.

To avoid timing errors or other race conditions in your script, if you have actions that load up a different page, you need to make sure that you wait for that action to finish before continuing.

script.js
1import { check } from 'k6';
2import { browser } from 'k6/experimental/browser';
3
4export const options = {
5 scenarios: {
6 ui: {
7 executor: 'shared-iterations',
8 options: {
9 browser: {
10 type: 'chromium',
11 },
12 },
13 },
14 },
15 thresholds: {
16 checks: ["rate==1.0"]
17 }
18}
19
20export default async function () {
21 const page = browser.newPage();
22
23 try {
24 await page.goto('https://test.k6.io/my_messages.php');
25
26 page.locator('input[name="login"]').type('admin');
27 page.locator('input[name="password"]').type('123');
28
29 const submitButton = page.locator('input[type="submit"]');
30
31 await Promise.all([page.waitForNavigation(), submitButton.click()]);
32
33 check(page, {
34 'header': p => p.locator('h2').textContent() == 'Welcome, admin!',
35 });
36 } finally {
37 page.close();
38 }
39}

The preceding code uses Promise.all([]) to wait for the two promises to be resolved before continuing. Since clicking the submit button causes page navigation, page.waitForNavigation() is needed because the page won't be ready until the navigation completes. This is required because there can be a race condition if these two actions don't happen simultaneously.

Then, you can use check from the k6 API to assert the text content of a specific element. Finally, you close the page and the browser.

Run both browser-level and protocol-level tests in a single script

The real power of the browser module shines when it’s combined with the existing features of k6. A common scenario that you can try is to mix a smaller subset of browser-level tests with a larger protocol-level test which can simulate how your website responds to various performance events. This approach is what we refer to as hybrid load testing and provides advantages such as:

  • testing real user flows on the frontend while generating a higher load in the backend
  • measuring backend and frontend performance in the same test execution
  • increased collaboration between backend and frontend teams since the same tool can be used

To run a browser-level and protocol-level test concurrently, you can use scenarios.

note

Keep in mind that there is an additional performance overhead when it comes to spinning up a browser VU and that the resource usage will depend on the system under test.

script.js
1import { browser } from 'k6/experimental/browser';
2import { check } from 'k6';
3import http from 'k6/http';
4
5export const options = {
6 scenarios: {
7 browser: {
8 executor: 'constant-vus',
9 exec: 'browserTest',
10 vus: 1,
11 duration: '10s',
12 options: {
13 browser: {
14 type: 'chromium',
15 }
16 }
17 },
18 news: {
19 executor: 'constant-vus',
20 exec: 'news',
21 vus: 20,
22 duration: '1m',
23 }
24 }
25};
26
27export async function browserTest() {
28 const page = browser.newPage();
29
30 try {
31 await page.goto('https://test.k6.io/browser.php');
32
33 page.locator('#checkbox1').check();
34
35 check(page, {
36 'checkbox is checked':
37 page.locator('#checkbox-info-display').textContent() === 'Thanks for checking the box',
38 });
39 } finally {
40 page.close();
41 }
42}
43
44export function news() {
45 const res = http.get('https://test.k6.io/news.php');
46
47 check(res, {
48 'status is 200': (r) => r.status === 200,
49 });
50}

The preceding code contains two scenarios. One for the browser-level test called browser and one for the protocol-level test called news. Both scenarios are using the constant-vus executor which introduces a constant number of virtual users to execute as many iterations as possible for a specified amount of time.

Since it's all in one script, this allows for greater collaboration amongst teams.