英文:
Get an array of class names for a Playwright element
问题
The most effective way to get an array of all class names for an element in Playwright using TypeScript is as follows:
export const getClassNames = async (locator: Locator): Promise<string[]> => {
// Make sure that we have exactly 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;
};
英文:
What is the most effective way to get an array of all class names for an element in Playwright using TypeScript?
I cannot seem to find any API for this very typical task and had to write the following:
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;
};
答案1
得分: 2
以下是您要翻译的内容:
在写作时似乎没有这样的函数,但您可以大大简化您的代码:
export const getClassNames = (locator: Locator): Promise<string[]> =>
locator.evaluate(el => [...el.classList]);
如果您正在严格模式下运行,.evaluate
已经断言只有一个元素,没有必要使用 Playwright 通常不建议使用的中间 ElementHandles。
这是一个可运行的概念验证:
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());
但如果您是为了测试断言的目的而这样做,请使用
await expect(locator).toHaveClass(["some", "classes"]);
如此答案所述。
英文:
There doesn't appear to be such a function at the time of writing, but you can shorten your code considerably:
export const getClassNames = (locator: Locator): Promise<string[]> =>
locator.evaluate(el => [...el.classList]);
If you're running in strict mode, .evaluate
already asserts that there's a single element, and there's no need for intermediate ElementHandles which Playwright generally advises against using.
Here's a runnable proof of concept:
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());
But if you're doing this for the purposes of a testing assertion, use
await expect(locator).toHaveClass(["some", "classes"]);
as described in this answer instead.
答案2
得分: 1
如果您正在验证元素的类,一种简洁的方法是:
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
英文:
If you are verifying on element's classes, an neat way:
const locator = page.locator('list > .component');
await expect(locator).toHaveClass(['component', 'component selected', 'component']);
You may also use regular expression in this:
await expect(locator).toHaveClass(/selected/);
Reference: https://playwright.dev/docs/api/class-locatorassertions#locator-assertions-to-have-class
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论