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

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

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:

  1. export const getClassNames = async (locator: Locator): Promise<string[]> => {
  2. // Make sure that we have exactly one element
  3. await expect(locator).toHaveCount(1);
  4. // Get the element
  5. const element = locator.first();
  6. // Use evaluateHandle to get an array of class names for the element
  7. const classListHandle = await element.evaluateHandle((el: Element) => Array.from(el.classList));
  8. // Get the result from the classListHandle
  9. const classNames = await classListHandle.jsonValue() as string[];
  10. return classNames;
  11. };
英文:

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:

  1. export const getClassNames = async (locator: Locator): Promise&lt;string[]&gt; =&gt; {
  2. // Make sure that we exctly one element
  3. await expect(locator).toHaveCount(1);
  4. // Get the element
  5. const element = locator.first();
  6. // Use evaluateHandle to get an array of class names for the element
  7. const classListHandle = await element.evaluateHandle((el: Element) =&gt; Array.from(el.classList));
  8. // Get the result from the classListHandle
  9. const classNames = await classListHandle.jsonValue() as string[];
  10. return classNames;
  11. };

答案1

得分: 2

以下是您要翻译的内容:

在写作时似乎没有这样的函数,但您可以大大简化您的代码:

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

如果您正在严格模式下运行,.evaluate 已经断言只有一个元素,没有必要使用 Playwright 通常不建议使用的中间 ElementHandles。

这是一个可运行的概念验证:

  1. const playwright = require("playwright"); // 1.30.0
  2. const classList = loc => loc.evaluate(el => [...el.classList]);
  3. let browser;
  4. (async () => {
  5. browser = await playwright.chromium.launch();
  6. const page = await browser.newPage();
  7. await page.setContent(`<p class="a b c"></p>`);
  8. console.log(await classList(page.locator("p"))); // => [ 'a', 'b', 'c' ]
  9. await page.setContent(`<p></p><p></p>`);
  10. console.log(await classList(page.locator("p")));
  11. // => strict mode violation: locator('p') resolved to 2 elements
  12. })()
  13. .catch(err => console.error(err))
  14. .finally(() => browser?.close());

但如果您是为了测试断言的目的而这样做,请使用

  1. 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:

  1. export const getClassNames = (locator: Locator): Promise&lt;string[]&gt; =&gt;
  2. 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:

  1. const playwright = require(&quot;playwright&quot;); // 1.30.0
  2. const classList = loc =&gt; loc.evaluate(el =&gt; [...el.classList]);
  3. let browser;
  4. (async () =&gt; {
  5. browser = await playwright.chromium.launch();
  6. const page = await browser.newPage();
  7. await page.setContent(`&lt;p class=&quot;a b c&quot;&gt;&lt;/p&gt;`);
  8. console.log(await classList(page.locator(&quot;p&quot;))); // =&gt; [ &#39;a&#39;, &#39;b&#39;, &#39;c&#39; ]
  9. await page.setContent(`&lt;p&gt;&lt;/p&gt;&lt;p&gt;&lt;/p&gt;`);
  10. console.log(await classList(page.locator(&quot;p&quot;)));
  11. // =&gt; strict mode violation: locator(&#39;p&#39;) resolved to 2 elements
  12. })()
  13. .catch(err =&gt; console.error(err))
  14. .finally(() =&gt; browser?.close());

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

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

as described in this answer instead.

答案2

得分: 1

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

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

您还可以在其中使用正则表达式:

  1. 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:

  1. const locator = page.locator(&#39;list &gt; .component&#39;);
  2. await expect(locator).toHaveClass([&#39;component&#39;, &#39;component selected&#39;, &#39;component&#39;]);

You may also use regular expression in this:

  1. 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:

确定