Documentation for automated readers
A curated documentation index is available at: https://grafana.com/llms.txt
A complete documentation index is available at: https://grafana.com/llms-full.txt
These indexes can help with page discovery before fetching individual documents.
This page is also available in Markdown, which may be easier for automated readers and AI tools to parse than HTML. The Markdown version is available at https://grafana.com/docs/k6/next/using-k6-browser/recommended-practices/clean-up-test-resources-page-close.md, or by sending Accept: text/markdown to https://grafana.com/docs/k6/next/using-k6-browser/recommended-practices/clean-up-test-resources-page-close/. For broader documentation discovery, the curated index is available at https://grafana.com/llms.txt and the complete index is available at https://grafana.com/llms-full.txt.
This is documentation for the next version of Grafana k6 documentation. For the latest stable release, go to the latest version.
Use Page.close to clean up test resources
When running k6 browser tests with event-based APIs, such as page.on, tests may not always properly flush metrics or clean up resources automatically, which can lead to incomplete metric reporting or leftover event handlers.
To prevent this, always call
page.close() at the end of your browser tests. Doing so ensures accurate and complete metric collection, cleans up event listeners to prevent resource leaks, and simplifies test teardown for improved reliability.
Example
import { browser } from "k6/browser";
import { check } from "k6";
const BASE_URL = __ENV.BASE_URL || "https://quickpizza.grafana.com/";
export const options = {
scenarios: {
ui: {
executor: "shared-iterations",
options: {
browser: {
type: "chromium",
},
},
},
},
};
export default async function () {
let checkData;
const page = await browser.newPage();
try {
await page.goto(BASE_URL);
checkData = await page.locator("h1").textContent();
check(page, {
header: checkData == "Looking to break out of your pizza routine?",
});
await page.locator('//button[. = "Pizza, Please!"]').click();
await page.waitForTimeout(500);
await page.screenshot({ path: "screenshot.png" });
checkData = await page.locator("div#recommendations").textContent();
check(page, {
recommendation: checkData != "",
});
} finally {
//Always close the page at the end
await page.close();
}
}Was this page helpful?
Related resources from Grafana Labs

