菜单
开源

on(event, handler)

注册一个处理程序,以便在指定事件发生时调用。

参数类型默认值描述
eventstring''要附加处理程序的事件。请参阅 支持的事件
handlerfunctionnull每次指定事件触发时要调用的函数。

活动

事件描述
console每次从页面 JavaScript 上下文调用 console API 方法时触发。传递给处理程序的参数由 ConsoleMessage 类定义。请参阅 示例
metric每次度量并为页面发出指标时触发。传递给处理程序的参数由 MetricMessage 对象定义。请参阅 示例
request每次页面发出请求时触发。处理程序会收到一个包含请求信息的 Request 对象。请参阅 示例
response每次页面收到响应时触发。处理程序会收到一个包含响应信息的 Response 对象。请参阅 示例

Console 事件示例

JavaScript
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://test.k6.io/');

    page.on('console', (msg) => {
      check(msg, {
        assertConsoleMessageType: (msg) => msg.type() == 'log',
        assertConsoleMessageText: (msg) => msg.text() == 'this is a console.log message 42',
        assertConsoleMessageArgs0: (msg) =>
          msg.args()[0].jsonValue() == 'this is a console.log message',
        assertConsoleMessageArgs1: (msg) => msg.args()[1].jsonValue() == 42,
      });
    });

    await page.evaluate(() => console.log('this is a console.log message', 42));
  } finally {
    await page.close(); // required so iteration can end
  }
}

Metric 事件示例

JavaScript
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();

  // We first register a handler using page.on('metric'). Calling page.on('metric')
  // multiple times is allowed. The registered handlers will be executed in the
  // order page.on was called.
  page.on('metric', (metric) => {
    // Using metric.tag finds a match between the current metric url and name
    // tags against the supplied regular expression in `url`.
    //
    // At the moment metric.tag is the only method on the metricMessage object.
    metric.tag({
      // This is the new name value that will replace the existing value in the
      // url and name tags when a match is found.
      name: 'test',
      // You can provide multiple matches here.
      matches: [
        {
          url: /^https:\/\/test\.k6\.io\/\?q=[0-9a-z]+$/,
          // When a method is defined it will also need to match on that too. If a
          // method is not provided it will match on all method types.
          method: 'GET',
        },
      ],
    });
  });

  try {
    // This is only for illustrative purposes, the q query param doesn't affect
    // the website.
    await page.goto('https://test.k6.io/?q=abc123');
    await page.goto('https://test.k6.io/?q=def456');
  } finally {
    await page.close();
  }
}

Request 和 Response 事件示例

JavaScript
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();

  // registers a handler that logs all requests made by the page
  page.on('request', async (request) => console.log(request.url()));
  // registers a handler that logs all responses received by the page
  page.on('response', async (response) => console.log(response.url()));

  await page.goto('https://quickpizza.grafana.com/', { waitUntil: 'networkidle' });
  await page.close();
}

输出

bash
INFO[0000] https://quickpizza.grafana.com/                  source=console
INFO[0001] https://quickpizza.grafana.com/api/tools         source=console
INFO[0001] https://quickpizza.grafana.com/images/pizza.png  source=console
...