Confirm button title by verifying part of the label that contains a space

I'm facing an issue with clicking a button using the following code:

await page.getByRole('button', { name: '3 Employees' }).click();

The problem is that the button's name fluctuates based on the number of employees, causing the hardcoded value to fail. Using a locator method with only the word 'Employees' could result in matching another button with the same locator and text. I also want to avoid using nth() method.

What I aim to achieve is modifying the code so it searches only for the 'Employees' part, including the space between 3 and 'Employees'. Is there any way to consider the 3 as a random value like "{randomvalue} Employees"?

Answer №1

When dealing with a specific button on a page, utilizing a regex can be effective as long as there are no other instances of /^\d+ Employees$/ elements present:

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

const html = `<!DOCTYPE html><html><body>
<button></button>
<script>
setTimeout(() => {
  document.querySelector("button").textContent =
    ~~(Math.random() * 100) + " Employees";
}, 3000);
</script>
</body></html>`;

test("{n} Employees button can be clicked", async ({page}) => {
  await page.setContent(html);
  await page.getByRole("button", {name: /^\d+ Employees$/}).click();
});

Make sure to take note of the ^ and $ anchors, which ensure an exact match excluding any leading/trailing whitespace. If you prefer to have a substring match, simply exclude these anchors.

If there are multiple elements that match this criteria, it might be beneficial to analyze the parent chain to pinpoint a specific button instead of relying on first/last/nth positions to avoid confusion.

Lastly, if there's a way to guarantee the rendering of a specific number of employees on the page, explore that option before resorting to the provided code. Only utilize the above code when all other approaches have been exhausted.

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

Using Typescript to incorporate Next.js on Firebase Functions

I'm currently working on deploying a Next.js application to Firebase Functions. import next from 'next' import {https} from 'firebase-functions' const server = next({ dev: process.env.NODE_ENV !== 'production', conf: ...

connecting and linking template content with an Observable

I have a CRUD page that needs to be updated after every operation. I have implemented Observable and the CRUD functions (specifically Add and Delete) are working fine, but I need to manually refresh the page to see the changes reflected. After trying to ...

You can only use a parameter initializer within the implementation of a function or constructor

I recently started learning TypeScript and am currently using it for React Bricks. I've been working on rendering a 3D object with three.js, but I keep encountering the error mentioned above. I've attempted various solutions such as passing color ...

Tips for restricting additional input when maximum length is reached in an Angular app

In my Angular 6 application, I am working on implementing a directive that prevents users from typing additional characters in an input field. However, I want to allow certain non-data input keys such as tab, delete, and backspace. Currently, I have an if ...

Update the Angular component once new data is saved in a separate Angular component

I've been diving into the world of MEAN stack and Angular, tackling a method within an angular component called itemListDetailsComponent (found in the .ts file) that looks something like this: onStatusUpdateClick() { this.activatedRoute.queryPar ...

An error occurred while trying to access properties of null, specifically the `_rawValidators` property

I recently upgraded an app from angular 8 to angular14 and encountered a problem with a form array. The error message I'm seeing is cfs-detail.component.html:13 ERROR TypeError: Cannot read properties of null (reading '_rawValidators'). It ...

Encountering TypeScript errors with React-Apollo when using GraphQL to pass props to a higher order component

I've encountered some challenges while attempting to link a React class component with my local Apollo cache data. Following the guidelines outlined here, I have run into issues where VSCode and Webpack are generating errors when I try to access data ...

Ensure that the method is passed a negative number -1 instead of the literal number 1 from an HTML error

This is an example of my HTML code: <button (mousedown)="onMouseDown($event, -1)"></button> Here is the TypeScript code for handling the mouse down event: onMouseDown(e: MouseEvent, direction: 1|-1) { this.compute.emit(direction); ...

Tips for choosing an HTML element using Playwright with TypeScript

My goal is to use playwright with typescript in order to select a specific html element. The element I am trying to target has the class "ivu-select-dropdown" and a specific style. <div class="ivu-select-dropdown" style="position: absolut ...

What is the best way to simulate a function within an object using Jest and Typescript?

I am currently working on a function that calls the url module. index.svelte import {url} from '@roxi/routify'; someFunction(() => { let x = $url('/books') // this line needs to be mocked console.log('x: ' + x); }); ...

Tips for successfully interacting with dynamic text areas using Protractor:

My current project involves e2e testing for an Angular 4 application with Protractor. Despite my efforts, I am struggling to locate a unique id, class, name or text identifier for a specific textarea within the application code. I need assistance in find ...

initiate an animated sequence upon the initialization of the Angular server

Is there a way to launch a Netflix animation after my server has started without success using setTimeout? I don't want to share the lengthy HTML and CSS code. You can view the code for the animation in question by visiting: https://codepen.io/claudi ...

Angular dependency issue: Expected '{' or ';' for @types/node

I encountered an error while running "ng serve" in my Angular application. Originally built as Angular 2, it was upgraded to Angular 8 (with attempts at versions 6 and 7 along the way). However, after migrating from Angular 5, I started experiencing errors ...

Is it acceptable to manipulate the prevState parameter of the setState function as mutable?

It is commonly known that directly modifying this.state is not recommended, and instead setState should be used. Following this logic, I assumed that prevState should also be treated as immutable, and setState should always involve creating a new object i ...

Issues with implementing AddEventListener in InAppBrowser on IONIC 2

I am currently working on implementing AddeventListener to listen for 'Exit' and 'LoadStart' events in InAppBrowser within IONIC2. Here is my HTML: <button (click)="browsersystem('https://www.google.com')" > Visit URL& ...

Error in Typescript: Function not being triggered on button click

As someone who is just starting out with typescript, I've been tackling a simple code that should display an alert message in the browser when a button is clicked. I've experimented with the button and input tags, as well as using both onclick ev ...

Tips for packaging a Node TypeScript/JavaScript library using Webpack

I am currently working on a Node project with the following setup: Written in Typescript Using Webpack and ts-loader for bundling Targeting Node.js +-proj/ +-src/ |-file1.ts |-file2.ts |-file3.ts |-... |-package.json |-webpack.confi ...

Nuxt - It is not possible to use useContext() within a watch() callback

I'm currently utilizing version 0.33.1 of @nuxtjs/composition-api along with Nuxt 2. Here's a snippet from my component: import { defineComponent, useContext, useRoute, watch } from '@nuxtjs/composition-api'; export default defineCompo ...

The 'undefined' type cannot be assigned to the '(number | null)[]' type

I recently encountered an issue with the following code snippet: const data = values?.map((item: PointDTO) => item.y); const chartData: ChartData = { labels, datasets: [{ data }], }; The error message I received is as follows: Type '(number | ...

Refining Typescript type with specific error for generics

Seeking assistance to comprehend the situation: TS playground The situation involves a store with an exec method, where narrowing down the type of exec param is crucial for a sub process. However, an error seems to arise due to the store type being generi ...