Is it possible to utilize a variable within the 'has-text()' function during playwright testing?

With Playwright, I am attempting to locate an element based on the value of a variable

For instance:

let username = 'Sully'
await page.click(`li:has-text(${username})`)

However, I encounter the following error:

page.click: Error: "has-text" engine expects a single string

Answer №1

Ensure to include either single or double quotes in the has-text method and make use of the name variable instead of sully or declare it beforehand.

Therefore, the correct syntax would look like this:

let name = 'Sully';

//                            ↓       ↓ - missing quotes       
await page.click(`li:has-text('${name}')`)

Answer №2

Avoid using direct CSS selectors or Page.click()

It is no longer recommended by our latest guidelines.

"Relying on XPath and CSS selectors that are tied to the DOM structure can lead to test failures when the structure changes. Lengthy chains of CSS or XPath selectors may result in inconsistent tests."

Page.click is strongly discouraged as well here.

Instead, utilize Locators with various filtering options:

Locators are adaptable and not reliant on the page layout.

 let name = 'Sully'
 await page
    .getByRole('listitem')
    .filter({ hasText: name})
    .click();

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

Steps to stop mat-spinner upon receiving Job Success/Failure Notification from the backend

I have a task that runs asynchronously and takes a long time to complete. When the task starts, I display a mat-spinner with a timeout set at 60000 milliseconds. However, we now have a notification service that provides updates on the job status. I would l ...

Unable to set textAlign column property in Inovua React Data Grid using typescript

I am currently facing an issue with centering the content of each grid cell in Inovua RDG. A frustrating TypeScript error keeps popping up: Type '{ name: string; header: string; textAlign: string; defaultFlex: number; defaultVisible?: undefined; }&apo ...

webpack is having trouble locating the src file, even though it should not be searching for it in the first place

I'm currently delving into the world of using TypeScript with React and am following a helpful tutorial at: https://blog.logrocket.com/how-why-a-guide-to-using-typescript-with-react-fffb76c61614 However, when attempting to run the webpack command thr ...

Examining the asynchronous function to cause an error using mocha

I am facing a challenge with testing an async function that is supposed to run for 2000ms before throwing an exception. Despite my efforts using Mocha / chai, the test does not seem to be working as expected. Here's what I have attempted: First appr ...

Guide to making a Typescript type guard for a ReactElement type

I'm currently working with three TypeScript type guards: const verifyTeaserOne = (teaser: Teaser): teaser is TeaserOneType => typeof teaser === 'object' && teaser.type.includes('One'); const validateTeaserTwo = ( ...

Tips for retrieving the present value of a piped/converted BehaviorSubject

How do I retrieve the current value of the observable generated by readValue() below without subscribing to it? var subject = new BehaviorSubject<Object>({}); observe(): Observable<Object> { return subject.pipe(map(mappingfunction)); } Do ...

Ionic 2 Media Plugin File Status with Ionic Native

In the Ionic Native Media plugin documentation found here, it mentions that there are both static and instance members, such as status. I am looking for an example related to the file status in the media plugin. I attempted to do this: console.log(this. ...

Why do my messages from BehaviorSubject get duplicated every time a new message is received?

Currently, I am using BehaviorSubject to receive data and also utilizing websockets, although the websocket functionality is not relevant at this moment. The main issue I am facing is why I keep receiving duplicated messages from BehaviorSubject. When exa ...

Discrepancies in ESLint outcomes during React app development

As a newcomer to React development, I am encountering discrepancies between the errors and warnings identified in my project's development environment versus its production environment. Strangely, I have not configured any differences between these en ...

Utilize Ant Design TreeSelect to seamlessly integrate API data into its title and value parameters

I am currently working on populating a Tree Select component in ANT Design with data fetched from an API. The response from the API follows this structure: projectData = ProjectData[]; export type ProjectData = { key?: number; projectId: number; ...

The element 'x' is not found within the 'unknown' type

I've been struggling with this issue. After searching through various sources like stackoverflow and github, I attempted a solution which involved adding a generic but I encountered the error message Expected 0 type arguments, but got 1. in relation t ...

The unknown number of arguments in a Typescript generic type

I'm currently working on developing a function that utilizes a generic type to take in a function, an array of arguments for the function, and then apply them accordingly. However, I am facing an issue with TypeScript not correctly interpreting the ar ...

Investigating TypeScript Bugs in Visual Studio Code

As I navigate through various sources, I notice that there is a plethora of information available on older versions of VSCode (v1.16.1 - the most recent version at the time of writing) or deprecated attributes in the launch.json file. I have experimented ...

Tips for adjusting the radio button value similarly to a checkbox in Angular 2 using *ngFor

my checkbox and radio button implementation: <input id="{{k.group_name}}_{{i}}" name="{{k.group_name}}" type="checkbox" class="hide" name="{{k.group_name}}" [value]="m.details" (change)="change($event, m , k.item_ingredient_group_key,false,k.maximum)"& ...

Node appears to be struggling to find the cors

I added the cors package and confirmed that it's inside the node_modules directory. However, I keep encountering this error message. /usr/src/app/node_modules/ts-node/src/index.ts:859 server | return new TSError(diagnosticText, diagnosticCodes, ...

Using template literals with Optional chaining in Javascript does not yield the expected results

Trying to implement template literal with optional chaining. type Item = { itemId:number, price: number}; type ItemType = { A:Item, B:Item }; const data : ItemType = { A:{itemId:1, price:2}, B:{itemId:2, price:3} }; let key = `data?.${variable}?.ite ...

The binding to 'videoId' cannot be established as it is not a recognized attribute of the 'youtube-player' component

Currently, I am working with Ionic 3 and Angular 5. In my application, I am integrating Youtube videos using ngx-youtube-player. However, I am encountering errors: Template parse errors: Can't bind to 'videoId' since it isn't a know ...

What is the method to group a TypeScript array based on a key from an object within the array?

I am dealing with an array called products that requires grouping based on the Product._shop_id. export class Product { _id: string; _shop_id: string; } export class Variant { variant_id: string; } export interface ShoppingCart { Variant: ...

Lerna and Create React App (CRA) problem: When using the command "lerna run --parallel start", the devServer does not initiate

I am currently working on managing 2 projects within lerna packages. One project is a package, and the other is a CRA website. When I run "yarn start" for each package individually, I can see the build folder and the website being loaded on the development ...

Changing Observable to Promise in Angular 2

Q) What is the best way to convert an observable into a promise for easy handling with .then(...)? The code snippet below showcases my current method that I am looking to transform into a promise: this._APIService.getAssetTypes().subscribe( assetty ...