typescript 获取Playwright元素的类名数组

t8e9dugd  于 2023-04-22  发布在  TypeScript
关注(0)|答案(2)|浏览(140)

使用TypeScript在Playwright中获取一个元素的所有类名的数组的最有效方法是什么?
我似乎找不到这个非常典型的任务的任何API,不得不编写以下代码:

export const getClassNames = async (locator: Locator): Promise<string[]> => {
    // Make sure that we exctly one element
    await expect(locator).toHaveCount(1);

    // Get the element
    const element = locator.first();

    // Use evaluateHandle to get an array of class names for the element
    const classListHandle = await element.evaluateHandle((el: Element) => Array.from(el.classList));

    // Get the result from the classListHandle
    const classNames = await classListHandle.jsonValue() as string[];

    return classNames;
};
xriantvc

xriantvc1#

在撰写本文时,似乎没有这样的函数,但您可以大大缩短代码:

export const getClassNames = (locator: Locator): Promise<string[]> =>
  locator.evaluate(el => [...el.classList]);

如果你在严格模式下运行,.evaluate已经Assert有一个元素,并且不需要中间的ElementHandles,Playwright通常建议不要使用。
下面是一个可运行的概念证明:

const playwright = require("playwright"); // 1.30.0

const classList = loc => loc.evaluate(el => [...el.classList]);

let browser;
(async () => {
  browser = await playwright.chromium.launch();
  const page = await browser.newPage();

  await page.setContent(`<p class="a b c"></p>`);
  console.log(await classList(page.locator("p"))); // => [ 'a', 'b', 'c' ]

  await page.setContent(`<p></p><p></p>`);
  console.log(await classList(page.locator("p")));
    // => strict mode violation: locator('p') resolved to 2 elements
})()
  .catch(err => console.error(err))
  .finally(() => browser?.close());

但如果这样做是为了测试Assert,则使用

await expect(locator).toHaveClass(["some", "classes"]);

this answer中所描述的。

zqry0prt

zqry0prt2#

如果你正在验证元素的类,一个简洁的方法是:

const locator = page.locator('list > .component');
await expect(locator).toHaveClass(['component', 'component selected', 'component']);

你也可以在下面的例子中使用正则表达式:

await expect(locator).toHaveClass(/selected/);

参考:https://playwright.dev/docs/api/class-locatorassertions#locator-assertions-to-have-class

相关问题