菜单
文档breadcrumb arrow Grafana k6breadcrumb arrow JavaScript APIbreadcrumb arrow k6/browserbreadcrumb arrow Pagebreadcrumb arrow waitForFunction(pageFunction, arg[, options])
开源

waitForFunction(pageFunction, arg[, options])

pageFunction 返回一个 truthy 值时返回。

参数类型默认值描述
pageFunctionfunction在页面上下文中执行的函数。
argstring''传递给 pageFunction 的可选参数
optionsobjectnull
options.pollingnumber 或 rafraf如果 polling'raf',则 pageFunction 会在 requestAnimationFrame 回调中不断执行。如果 polling 是一个数字,则它被视为函数执行的时间间隔(毫秒)。
options.timeoutnumber30000最大时间(毫秒)。传入 0 可禁用超时。默认值会被 BrowserContextPage 上的 setDefaultTimeout 选项覆盖。

返回值

类型描述
Promise< JSHandle>与页面关联的 JSHandle 实例。

示例

JavaScript
import { browser } from 'k6/browser';
import { check } from 'https://jslib.k6.io/k6-utils/1.5.0/index.js';

export const options = {
  scenarios: {
    browser: {
      executor: 'shared-iterations',
      options: {
        browser: {
          type: 'chromium',
        },
      },
    },
  },
};

export default async function () {
  const page = await browser.newPage();

  try {
    await page.evaluate(() => {
      setTimeout(() => {
        const el = document.createElement('h1');
        el.innerHTML = 'Hello';
        document.body.appendChild(el);
      }, 1000);
    });

    const ok = await page.waitForFunction("document.querySelector('h1')", {
      polling: 'mutation',
      timeout: 2000,
    });
    await check(ok, {
      'waitForFunction successfully resolved': async (ok) =>
          await ok.innerHTML() == 'Hello'
    });
  } finally {
    await page.close();
  }
}