Locator
Locator API 使处理动态变化的元素更加容易。与现有定位元素的方法(例如 Page.$()
)相比,它的一些优点包括
- 即使底层帧导航,也能通过查找元素来帮助编写健壮的测试。
- 使处理使用 Svelte、React、Vue 等构建的动态网页和 SPA 变得更容易。
- 支持使用 Page Object 模型 (POM) 模式等测试抽象来简化和组织测试。
- 所有
locator
方法都启用了strict
模式,这意味着如果多个元素匹配给定选择器,将抛出错误。
Locator 可以使用 page.locator(selector[, options]) 方法创建。
示例
import { browser } from 'k6/browser';
export const options = {
scenarios: {
browser: {
executor: 'shared-iterations',
options: {
browser: {
type: 'chromium',
},
},
},
},
};
export default async function () {
const page = await browser.newPage();
try {
await page.goto('https://test.k6.io/flip_coin.php');
/*
In this example, we will use two locators, matching a
different betting button on the page. If you were to query
the buttons once and save them as below, you would see an
error after the initial navigation. Try it!
const heads = await page.$("input[value='Bet on heads!']");
const tails = await page.$("input[value='Bet on tails!']");
The Locator API allows you to get a fresh element handle each
time you use one of the locator methods. And, you can carry a
locator across frame navigations. Let's create two locators;
each locates a button on the page.
*/
const heads = page.locator("input[value='Bet on heads!']");
const tails = page.locator("input[value='Bet on tails!']");
const currentBet = page.locator("//p[starts-with(text(),'Your bet: ')]");
// In the following Promise.all the tails locator clicks
// on the tails button by using the locator's selector.
// Since clicking on each button causes page navigation,
// waitForNavigation is needed -- this is because the page
// won't be ready until the navigation completes.
// Setting up the waitForNavigation first before the click
// is important to avoid race conditions.
await Promise.all([page.waitForNavigation(), tails.click()]);
console.log(await currentBet.innerText());
// the heads locator clicks on the heads button
// by using the locator's selector.
await Promise.all([page.waitForNavigation(), heads.click()]);
console.log(await currentBet.innerText());
await Promise.all([page.waitForNavigation(), tails.click()]);
console.log(await currentBet.innerText());
} finally {
await page.close();
}
}