Managing dynamic text within a label using Playwright

In my Playwright Typescript test, I have the following code snippet:

await page.goto('https://demoqa.com/');
await page.getByLabel('Optionen verwalten', { exact: true }).click();
await page.locator('label').filter({ hasText: 'Berechtigtes Interesse (32' }).locator('span').nth(2).click();
await page.locator('label').filter({ hasText: 'Berechtigtes Interesse (49' }).locator('span').nth(2).click();
await page.locator('label').filter({ hasText: 'Berechtigtes Interesse (16' }).locator('span').nth(2).click();
await page.locator('label').filter({ hasText: 'Berechtigtes Interesse (22' }).locator('span').nth(2).click();
await page.locator('label').filter({ hasText: 'Berechtigtes Interesse (40' }).locator('span').nth(2).click();
await page.locator('label').filter({ hasText: 'Berechtigtes Interesse (3 Anbieter' }).locator('span').nth(2).click();
await page.getByRole('button', { name: 'Auswahl bestätigen' }).click();

The HTML contains multiple labels, here are two examples:

<label class="fc-preference-slider-container fc-consent-preference-container"><span class="fc-preference-slider-label">Einwilligung (77&nbsp;Anbieter)</span><span class="fc-preference-slider"><input type="checkbox" role="button" aria-label="Einwilligung (77&nbsp;Anbieter), Verwendung reduzierter Daten zur Auswahl von Werbeanzeigen" aria-pressed="false" tabindex="0" class="fc-preference-consent purpose" data-id="2"><span class="fc-slider-el"></span></span></label>
<label class="fc-preference-slider-container fc-legitimate-interest-preference-container" for="fc-preference-slider-purpose-2"><span class="fc-preference-slider-label">Berechtigtes Interesse (32&nbsp;Anbieter)<button class="fc-help-tip" data-title="Was bedeutet ein berechtigtes Interesse?" data-full-info="Einige Anbieter bitten Sie nicht um Ihre Einwilligung, sondern nutzen Ihre personenbezogenen Daten auf Grundlage ihres berechtigten Interesses." role=&...

To deselect all options with aria-pressed="true", I need to find a more robust locator because the label text may change. I can use the unique id for that slider:

const slider2 = page.locator('[id$="fc-preference-slider-purpose-2"]');

But how do I adjust the code to click on the associated slider?

Answer №1

One possible approach is to utilize regex in order to target the label. It seems that there is a specific pattern involving {text} ({number} {text}):

await page.locator('label')
  .filter({ hasText: /^[\w ]+\(\d+ [\w ]+\)$/ })

If you have the ability to modify the HTML, a more efficient method would be to include a data-testid="your-id" attribute and then implement a simplified query:

await page.getByTestId('your-id')

Answer №2

getByLabel function operates on a substring matching basis, which could be suitable for your specific scenario:

import {expect, test} from "@playwright/test"; // ^1.39.0

const html = `<!DOCTYPE html><html><body>
<input
  type="checkbox"
  role="button"
  aria-label="Berechtigtes Interesse (32&nbsp;Anbieter), Verwendung reduzierter Daten zur Auswahl von Werbeanzeigen"
  aria-pressed="true"
  tabindex="0"
  class="fc-preference-legitimate-interest purpose"
  data-id="2"
  id="fc-preference-slider-purpose-2"
  checked=""
>
</body></html>`;

test("input is selectable via partial label substring", async ({page}) => {
  await page.setContent(html);
  const label = "Verwendung reduzierter Daten zur Auswahl von Werbeanzeigen";
  await expect(page.getByLabel(label)).toBeVisible();
});

If you require more accuracy, an alternative approach is using a CSS attribute selector $ to search based on the end of the attribute value:

// ...
  const input = page.locator(
    '[aria-label$="Verwendung reduzierter Daten zur Auswahl von Werbeanzeigen"]'
  );
  await expect(input).toBeVisible();
// ...

The usage of .locator('span').nth(2) seems unrelated to your HTML structure; it's not recommended as it doesn't verify user-visible behavior. Providing additional context can help in avoiding such practices.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Automatic type inference for functions in TypeScript with arguments

I am looking to define an interface with the following structure: interface CheckNActSetup<D, C> { defs: (event: Event) => D, context: (defs: D) => C; exec: (context: C) => any[]; when: ((context: C) => boolean)[]; } and implement it usi ...

Encountering a problem during the installation of angular-route.d.ts

When trying to install angular-route using the command typings install angular-route --save -global, I encountered an error. Can someone help me resolve this issue? typings ERR! message Unable to find "angular-route" ("npm") in the registry. typings ERR! ...

Invalid Redux store: Element type is not valid; a string type is expected

I am running into an issue while setting up the redux store with typescript for the first time. The error message I am encountering is: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) ...

Tips for setting up a React TypeScript project with custom folder paths, such as being able to access components with `@components/` included

I'm looking to streamline the relative url imports for my React TypeScript project. Instead of using something messy like ../../../contexts/AuthContext, I want to simplify it to just @contexts/AuthContexts. I attempted to update my tsconfig.json with ...

The type is lacking the property onAuxClickCapture and onAuxClick

When utilizing forwardRef from React, an unexpected type error occurs: The type '{ children: ReactNode; }' is lacking the properties specified in 'Pick<ILinkProps, "className" | "children" | "accept" | "acceptCharset" | "action" | ... 34 ...

Leveraging moment.format Function in Angular within an HTML Context

Is there a way to implement the moment.format method in HTML? Currently, I am utilizing the toLocaleDateString method to showcase an array of dates: <ng-template let-event> <div>{{event.date.toLocaleDateString(' ...

Setting the response type to text in Angular 6 when making an http call

Attempting to send an HTTP request to the Spring REST API, which returns a string value ('success' or 'fail'). However, I am uncertain of how to specify the response type as a string value when making the call to the API. The error mess ...

Issue encountered when importing a font in TypeScript due to an error in the link tag's crossorigin

How do I troubleshoot a TypeScript error when importing a custom font, such as a Google font? <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> Below is the specific error message: Type 'boolean' is ...

The Child/Parent arguments in Typescript methods cannot be assigned

Why is this not working in TypeScript? class Parent { id: string = '' } class Child extends Parent{ name: string = '' } const fails: (created: Parent) => void = (created: Child) => { return }; const failsToo: ({ create ...

Create a prop type that can be either a single number or an array of numbers, depending on the value of another

Seeking a solution, I am exploring an example using arrays with the 'multi' property. When 'multi' is true, the items should be of type number[]. Otherwise, they should be of type number. interface EnhancedSelectProps { items: multi ? ...

Prevent methods from being called in a Typescript class after they have already

I encountered a scenario where I need to exclude certain methods from the return type of a class method once they have been called. Consider a class named Setup with methods step1, step2, and step3. class Setup { step1() { return this; } ...

Unable to loop through the Array

let Users = [ { name: 'John', id: '1', jp: 'USA' }, { name: 'Jane', id: '2', jp: 'Japan' }, ]; export function DisplayUsers(usersList) { return ( <div> {usersList?.map((user ...

Looking for a JavaScript (Angular) event listener to trigger when closing pages and tabs

I am looking for an event that will only work when closing a page or tab, but should not be triggered when the page is refreshed. I am aware of the "beforeunload" event, but it also gets activated on page refresh. Below is the code snippet I am currently ...

<Click here to navigate to page 2> await whenClicked={navigation.navigate("page_2")} />

Issue with assigning a 'string' to a parameter in TypeScript while trying to navigate to another screen in React Native. Can anyone help with this error? This problem occurs when we want to navigate to another screen using TypeScript in React Na ...

Deactivating the drag feature when setting the duration of a new event in FullCalendar

Hello there! I've integrated full calendar into my Angular project and I'm facing a challenge. I want to restrict users from defining the duration of an event by holding click on an empty schedule in the weekly calendar, where each date interval ...

Is there a way to combine compiling TypeScript and running the resulting .js file into one build command in Sublime Text 3?

I have successfully installed the TypeScript plugin on Sublime Text 3. Once installed, a build system is added to the menu for easy access. https://i.stack.imgur.com/m21bT.png You can simply press "Command + B" to build a .ts file. My goal is to compile ...

The error message states that the property "user" is not found in the type "Session & Partial<SessionData>"

I recently had a javascript code that I'm now attempting to convert into typescript route.get('/order', async(req,res) => { var sessionData = req.session; if(typeof sessionData.user === 'undefined') { ...

Accessing node_modules in TypeScript within an Asp.Net Core application

As I work on building a straightforward ASP.NET Core application utilizing npm and TypeScript, the structure of my project is organized as follows: / root | wwwroot | js | AutoGenerated // <-- TS output goes here | view | i ...

Encountering an issue during the registration of reducers with ActionReducerMap: "does not match the type 'ActionReducerMap<AppState, Action>'"

Here is a simplified version of my Angular 5 application. I have a reducer that needs to be registered in the root module. The problem arises in LINE A where I encounter the following error: ERROR in src/app/store/app.reducers.ts(7,14): error TS2322: Type ...

Issue with React not displaying JSX when onClick Button is triggered

I've recently started learning React and I'm facing a problem that I can't seem to figure out. I have a basic button, and when it's clicked, I want to add another text or HTML element. While the console log statement is working fine, th ...