grafana / k6-docs

The k6 documentation website.
https://grafana.com/docs/k6/latest/
88 stars 223 forks source link

Add k6 browser tutorial for validating that a page has loaded #1779

Open heitortsergent opened 1 month ago

heitortsergent commented 1 month ago

Feedback from @tom-miseur and user, we're missing a simple tutorial explaining how a user can check that a page has successfully loaded.

Example from @tom-miseur:

The most reliable way to check that a page has successfully loaded is to look for a specific web element to appear once an action has been performed.

To demonstrate:

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 {
    await page.goto('https://www.google.com/');
  } finally {
    await page.close();
  }
}

This will navigate to google.com, but there's no validation beyond that. Unless the page timed out, page.goto isn't going to throw an exception.

A good element to look for on the google homepage is the ubiquitous search box, which can be identified using the selector/locator //textarea[@name="q"]. So we can add that in after the page.goto navigation like this to validate that it is visible:

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://www.google.com/');

    const searchBoxVisible = await page.locator('//textarea[@name="q"]').isVisible();

    check(searchBoxVisible, {
      'Search box is visible': (e) => e === true,
    });
  } finally {
    await page.close();
  }
}