Rayrun

How do I check if a specific dataset value exists using Playwright?

Answer

To check if a specific dataset value exists using @playwright/test, you can use the getAttribute method to retrieve the data attribute of an element and then use the expect(value).toBeDefined() method to ensure that the dataset value is defined.

Here's an example:

import { test, expect } from '@playwright/test';

test('Check dataset value existence', async ({ page }) => {
  await page.goto('https://ray.run/example');

  const element = await page.$('#my-element');
  const myValue = await element.getAttribute('data-my-value');
  expect(myValue).toBeDefined();
});

In this example, you navigate to the example page, retrieve an element with the ID "my-element", and get its "data-my-value" attribute using getAttribute. Then, you assert that this attribute is defined using toBeDefined().

If you want to check for the existence of a specific dataset key, you can retrieve all data attributes of an element and then check if your desired key exists in that object. For example:

import { test, expect } from '@playwright/test';

test('Check dataset key existence', async ({ page }) => {
  await page.goto('https://ray.run/example');

  const element = await page.$('#my-element');
  const dataAttributes = await element.getAttribute('data');
  expect(dataAttributes).toContain('my-key');
});

In this case, you get all the data attributes using getAttribute and then check if "my-key" exists in those attributes using toContain.

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].