This is documentation for the next version of Grafana k6 documentation. For the latest stable release, go to the latest version.
waitForEvent(event[, optionsOrPredicate])
Waits for the specified event to be emitted. This is a generic method that can wait for any page event such as console, request, or response.
Returns
Examples
Wait for console message
import { browser } from 'k6/browser';
export const options = {
scenarios: {
ui: {
executor: 'shared-iterations',
options: {
browser: {
type: 'chromium',
},
},
},
},
};
export default async function () {
const page = await browser.newPage();
try {
// Set up the wait before triggering the action
const consolePromise = page.waitForEvent('console');
// Trigger action that causes a console message
await page.evaluate(() => console.log('hello from page'));
const msg = await consolePromise;
console.log(`Console message: ${msg.text()}`);
} finally {
await page.close();
}
}Wait for response with predicate
import { browser } from 'k6/browser';
import { check } from 'k6';
export const options = {
scenarios: {
ui: {
executor: 'shared-iterations',
options: {
browser: {
type: 'chromium',
},
},
},
},
};
export default async function () {
const page = await browser.newPage();
try {
await page.goto('https://quickpizza.grafana.com/');
// Wait for a specific response using a predicate function
const responsePromise = page.waitForEvent('response', (res) =>
res.url().includes('/api/pizza')
);
await page.getByRole('button', { name: /pizza/i }).click();
const response = await responsePromise;
check(response, {
'response status is 200': (r) => r.status() === 200,
});
} finally {
await page.close();
}
}Best practices
- Set up promise before trigger: Always set up the
waitForEventpromise before triggering the action that causes the event:
// Correct
const eventPromise = page.waitForEvent('console');
await page.evaluate(() => console.log('test'));
const msg = await eventPromise;
// Incorrect - may miss the event
await page.evaluate(() => console.log('test'));
const msg = await page.waitForEvent('console');- Use specific methods when available: For common use cases, prefer the more specific methods like
waitForRequestorwaitForResponsewhich provide URL pattern matching.
Related
- page.on() - Subscribe to page events
- page.waitForRequest() - Wait for HTTP requests with URL pattern matching
- page.waitForResponse() - Wait for HTTP responses with URL pattern matching


