获取一个 Playwright 元素的类名数组。

huangapple go评论75阅读模式
英文:

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&lt;string[]&gt; =&gt; {
	// 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) =&gt; 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&lt;string[]&gt; =&gt;
  locator.evaluate(el =&gt; [...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(&quot;playwright&quot;); // 1.30.0

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

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

  await page.setContent(`&lt;p class=&quot;a b c&quot;&gt;&lt;/p&gt;`);
  console.log(await classList(page.locator(&quot;p&quot;))); // =&gt; [ &#39;a&#39;, &#39;b&#39;, &#39;c&#39; ]

  await page.setContent(`&lt;p&gt;&lt;/p&gt;&lt;p&gt;&lt;/p&gt;`);
  console.log(await classList(page.locator(&quot;p&quot;)));
    // =&gt; strict mode violation: locator(&#39;p&#39;) resolved to 2 elements
})()
  .catch(err =&gt; console.error(err))
  .finally(() =&gt; browser?.close());

But if you're doing this for the purposes of a testing assertion, use

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

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(&#39;list &gt; .component&#39;);
await expect(locator).toHaveClass([&#39;component&#39;, &#39;component selected&#39;, &#39;component&#39;]);

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

huangapple
  • 本文由 发表于 2023年4月17日 17:15:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76033517.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定