Running browser tests
Follow along to learn how to:
- Run a test
- Interact with elements on your webpage
- Wait for page navigation
- Run both browser-level and protocol-level tests in a single script
Run a test
To run a simple local script:
Copy the following code, paste it into your favorite editor, and save it as
script.js
.Note that providing an
executor
and setting thebrowser
scenario option’stype
tochromium
is mandatory. Please see the options and scenarios documentation for more information.import { browser } from 'k6/browser'; export const options = { scenarios: { ui: { executor: 'shared-iterations', options: { browser: { type: 'chromium', }, }, }, }, thresholds: { checks: ['rate==1.0'], }, }; export default async function () { const page = await browser.newPage(); try { await page.goto('https://test.k6.io/'); await page.screenshot({ path: 'screenshots/screenshot.png' }); } finally { await page.close(); } }
The preceding code imports the
browser
the browser module), and uses itsnewPage
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
Starting from v0.52.0 the browser module API has been converted to an asynchronous API. That means that most of the methods now return promises. Refer to the migration guide to learn more about the changes and how to update your scripts.
Then, run the test on your terminal with this command:
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.
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.
Optional step: running browser tests in Docker on Mac computers with Apple Silicon:
Make sure you’re running the latest Docker version.
Update Rosetta and export an environment variable with the following:
softwareupdate --install-rosetta && export DOCKER_DEFAULT_PLATFORM=linux/amd64
Select VirtuoFS in Settings > General > VirtuoFS.
Enable the Rosetta emulation in Settings > Features in development > Use Rosetta for x86/amd64 emulation on Apple Silicon.
Restart Docker.
Run the browser image with the following command (adds the
--platform
flag):docker run --rm -i --platform linux/amd64 -v $(pwd):/home/k6/screenshots -e K6_BROWSER_HEADLESS=false grafana/k6:master-with-browser run - <script.js