当你使用locator.evaluateAll() https://playwright.dev/docs/api/class-locator#locator-evaluate-all,您在回调中得到一个数组。我会调用参数nodes
而不是node
所以你很清楚你需要迭代它。
第二个问题:地图不容易序列化。尝试一下:
const m = new Map();
m.set("hello", "world");
console.log(m.get("hello")); // => "world"
console.log(JSON.stringify(m)); // => {}
所有传入和传出的数据evaluate
调用将被反/序列化,这将破坏你的地图。除非你有一些令人信服的理由来使用地图,否则我只会使用一个普通的旧对象。
这是一种选择:
import {expect, test} from "@playwright/test"; // ^1.30.0
test("playwright docs page has correct headers", async ({page}) => {
const url = "https://playwright.dev/docs/api-testing";
await page.goto(url, {waitUntil: "domcontentloaded"});
const headers = await page.locator("h2").evaluateAll(nodes =>
Object.fromEntries(
nodes.map(node => [node.id, node.textContent.trim()])
)
);
const expected = {
"writing-api-test": "Writing API Test",
"using-request-context": "Using request context",
"sending-api-requests-from-ui-tests": "Sending API requests from UI tests",
"reusing-authentication-state": "Reusing authentication state",
"context-request-vs-global-request": "Context request vs global request",
};
expect(headers).toEqual(expected);
});
请注意,您不需要await
一个定位器定义,只有一个操作。通常使用.textContent
而不是.innerText
。修剪 HTML 字符串以使其标准化。留意有趣的事情​
这些标题中的 s (考虑仅抓取文本节点并忽略<a>
)。无需await
非定位器断言。
尽管如此,上述方法并不完全是最佳实践,因为它不使用网络优先 https://playwright.dev/docs/best-practices#use-web-first-assertions断言。我会重写它以使用.toHaveText()
直接在定位器上。
await expect(page.locator("h2")).toHaveText([
"Writing API Test",
"Using request context",
"Sending API requests from UI tests",
"Reusing authentication state",
"Context request vs global request",
]);
id 可以单独测试,而且可能并不那么重要。你可以poll https://playwright.dev/docs/test-assertions#polling or retry https://playwright.dev/docs/test-assertions#retrying等待谓词为真作为最后的手段,但如果你确定这些总是静态地出现在页面上,那么打破网络优先规则可能是可以的。