Create a k6 browser check
This tutorial shows how to create your first k6 browser check.
k6 browser checks use the k6 OSS engine in the background, and give you the flexibility to create checks with complex logic and workflows by writing a JavaScript script.
In this tutorial you will:
- Create a k6 browser check using the
test-api.k6.io
service. The check will:- Log in using a pre-defined
synthetics_multihttp_example
account. - Add an object to the user’s list, then delete it.
- Log in using a pre-defined
- Set up assertions for each request to ensure they’re working as expected.
Before you begin
To complete this tutorial, you’ll need:
- A Grafana instance with Synthetic Monitoring set up.
- Optionally, follow the Create a MultiHTTP check tutorial or Create a k6 scripted check tutorial first. These tutorials go through a similar workflow without using a browser, and can give you a better understanding of when to use a MultiHTTP, k6 scripted or k6 browser check, depending on your use case.
Note
This tutorial uses thetest-api.k6.io
service, which is a public shared environment. You can use it and follow along this tutorial, but it’s recommended to avoid high-load tests. The service is also open source if you’d like to deploy a private instance.
Create a k6 browser check
To create a k6 browser check:
- Open your Grafana instance.
- On the main menu, select Testing & Synthetics.
- Click Synthetics.
- Click Add new check.
- Select Create browser check.
After that, you will see the New browser check page where you can configure your new check. The first step is to define the check:
- Fill out Job name and Instance.
The next step is to add the script that runs on every check execution.
Log in to an application
The Script code editor is where you can configure the page and page elements you want the k6 browser check to test. The check comes with an example script that you can use as a starting point.
For this tutorial, the first step is to log in to the test-api.k6.io
application by filling in the username and password fields and clicking the Login button. The test asserts that after clicking the login button, the browser successfully loads the My Crocodiles page.
import { browser } from 'k6/browser';
import { check } from 'https://jslib.k6.io/k6-utils/1.5.0/index.js';
export const options = {
scenarios: {
ui: {
executor: 'shared-iterations',
options: {
browser: {
type: 'chromium',
},
},
},
},
};
export default async function () {
const context = await browser.newContext();
const page = await context.newPage();
const baseUrl = 'https://test-api.k6.io/';
const startUrl = `${baseUrl}api-auth/login/?next=/my/crocodiles/`;
try {
await page.goto(startUrl);
// Step 1: Log in
await page.locator('input[name="username"]').type('synthetics_multihttp_example');
await page.locator('input[name="password"]').type('synthetics_multihttp_example');
const loginButton = page.locator('input[name="submit"]');
await Promise.all([page.waitForNavigation(), loginButton.click()]);
const header = await page.locator('h1').textContent();
await check(header, {
'Loaded My Crocodiles Page': (h) => h == 'My Crocodiles',
});
} finally {
await page.close();
}
}
It’s important to set up assertions for each request you make. That way you can have Synthetic Monitoring automatically validate things such as the existence of certain elements on the page.
Create and delete an object
The next step is to create a crocodile in the test application, and then grab the newly created ID to delete the crocodile.
import { browser } from 'k6/browser';
import { check } from 'https://jslib.k6.io/k6-utils/1.5.0/index.js';
import { fail } from 'k6';
export const options = {
scenarios: {
ui: {
executor: 'shared-iterations',
options: {
browser: {
type: 'chromium',
},
},
},
},
};
export default async function () {
const context = await browser.newContext({
viewport: {
width: 1920,
height: 1080,
},
});
const page = await context.newPage();
const baseUrl = 'https://test-api.k6.io/';
const startUrl = `${baseUrl}api-auth/login/?next=/my/crocodiles/`;
try {
await page.goto(startUrl);
// Step 1: Log in
await page.locator('input[name="username"]').type('synthetics_multihttp_example');
await page.locator('input[name="password"]').type('synthetics_multihttp_example');
const loginButton = page.locator('input[name="submit"]');
await Promise.all([page.waitForNavigation(), loginButton.click()]);
const header = await page.locator('h1').textContent();
await check(header, {
'Loaded My Crocodiles Page': (h) => h == 'My Crocodiles',
});
// Step 2: Create a new crocodile
await page.locator('input[name="name"]').type('synthetics test object');
await page.locator('select[name="sex"]').selectOption('F');
await page.locator('input[name="date_of_birth"]').fill('2024-09-25');
const submitButton = page.locator('#post-object-form > form > fieldset > div.form-actions > button');
await Promise.all([page.waitForNavigation(), submitButton.click()]);
const responseText = await page.locator('[aria-label="response info"]').textContent();
console.log(responseText);
(await check(responseText, {
'Created crocodile': (t) => t.trim().startsWith('HTTP 201 Created'),
})) || fail('did not create crocodile');
const match = /\"id\": ([0-9]+),/g.exec(responseText);
if (match === null) {
fail('Could not fetch crocodile ID');
}
// Step 3: Delete the crocodile
const objectId = match[1];
console.log(`Deleting crocodile ${objectId} id`);
const deletePage = `${baseUrl}my/crocodiles/${objectId}/`;
await page.goto(deletePage);
const deleteButton = page.locator('//button[text()="DELETE"]');
await deleteButton.click();
const confirmDeleteButton = page.locator('//button[text()="Delete"]');
await Promise.all([page.waitForNavigation(), confirmDeleteButton.click()]);
const deleteResponseText = await page.locator('[aria-label="response info"]').textContent();
console.log(deleteResponseText);
(await check(deleteResponseText, {
'Deleted crocodile': (t) => t.trim().startsWith('HTTP 204 No Content'),
})) || fail('did not delete crocodile');
} finally {
await page.close();
}
}
You can copy the script example to the Script section of your check.
Set probe locations and frequency
Next, you have to configure the Probes, which represent the locations where you want to run your test from, and how frequent you want your check to run:
- Click Execution in the sidebar.
- Select at least one probe from the Probe locations drop-down.
- You can leave the Frequency field with the default value.
Next, click Test at the end of the screen to make sure your check is working correctly, and then click Submit.
Your check will now run from the probe locations that you selected, and with the default frequency value. Your check will make sure that the endpoints you configured are working correctly, and if you have any issues, you will be able to see them in your check dashboard.
Next steps
Now that you have a k6 browser check configured, you can:
- Refer to k6 browser check to get more information about the metrics and options available for the k6 browser check type.
- Refer to Synthetic Monitoring alerting to learn how to create and configure alerts in case your check fails.
- Refer to the Grafana Cloud k6 documentation to learn about performance testing, and how you can reuse the same script you created in this tutorial to run a performance test.