Puppeteer: What is the best way to interact with a button that has a specific label?

When trying to click on a button with a specific label, I use the following code:

const button = await this.page.$$eval('button', (elms: Element[], label: string) => {
    const el: Element = elms.find((el: Element) => el.textContent === label)
    console.log(el);
    return el;
}, label);
await button.click(); // button is undefined

Despite seeing the element in the browser console when using console.log() and being able to .click() on it, the returned value does not make it into the 'button' variable.

This discrepancy raises the question:

According to the documentation for $$eval:

returns: > Promise which resolves to the return value of pageFunction

Answer №1

When using the $$eval function, make sure you are not trying to return a DOM element because they are not serializable and will result in an undefined variable. Check out the MDN documentation for more information on serialization.

Referencing the official docs, it states:

If the value returned by page.evaluate is not serializable, it will resolve to undefined.

Answer №2

Another option is to search for the desired element within the evaluate function and trigger a click event from there.

await page.evaluate(buttonText => {
    $(`button:contains('${buttonText}')`)[0].click()
}, buttonText)

There is no need to return the element in order to click on it.

In line with Vaviloff's explanation, the issue of 'the return value not reaching the button' occurs because

If the function executed by page.evaluate produces a non-serializable output, then page.evaluate will resolve as undefined

Answer №3

After taking into account the suggestions from the answers provided earlier, this is the code snippet that I have come up with:

await this.page.$$eval('button', (elements: Element[], text: string) => {
    const buttonToClick = elements.find(element => element.textContent === text) as HTMLElement;
    if(buttonToClick){
        buttonToClick.click();
    }
}, buttonText);

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

Ways to RESOLVE implicit any for accessing array property

Check out the code snippet below: function getUsername(): string { return 'john_doe'; } function sampleFunction(): void { const data = {}; const username: string = getUsername(); const age: any = 30; data[username] = age; // ...

Ensuring the validation of JSON schemas with dynamically generated keys using Typescript

I have a directory called 'schemas' that holds various JSON files containing different schemas. For instance, /schemas/banana-schema.json { "$schema": "http://json-schema.org/draft-06/schema", "type": "object", "properties": { "banan ...

TypeScript: creating an interface property that relies on the value of another

Is it feasible to have an interface property that relies on another? For instance, consider the following: const object = { foo: 'hello', bar: { hello: '123', }, } I wish to ensure that the key in bar corresponds to the value of f ...

Angular 2 Unit test issue: Unable to resolve parameters for 'RequestOptions' class

I am currently working on testing a simple component that has some dependencies. One of the requirements is to provide certain providers for the test. /* tslint:disable:no-unused-variable */ import { By } from '@angular/platform-browser&ap ...

Data is not displaying correctly in the Angular Material Table

I'm currently trying to build a mat table based on an online tutorial, but I'm facing a problem where the table appears empty even though I have hard coded data. As someone new to Angular and HTML/CSS, I'm struggling to understand why the ma ...

Exploring the power of Angular 10 components

Angular version 10 has left me feeling bewildered. Let's explore a few scenarios: Scenario 1: If I create AComponent.ts/html/css without an A.module.ts, should I declare and export it in app.module.ts? Can another module 'B' use the 'A ...

Using vue-class-component: A guide on creating and setting up reactive data

I am currently working with Vue.js using TypeScript and vue-class-component. My goal is to create a custom component with reactive data. Below is the code I have so far: <template> <div> <input v-model="data.name" placeholder=" ...

Storing information from JSON into an object

I am encountering an issue regarding transferring data from JSON to an object. Although this solution is functional, it is not entirely satisfactory. Take a look at the service. Is there an improved method for handling data conversion from this JSON to an ...

Selecting a filter for an array of objects

I'm struggling to implement a search feature in my mat-select DropDown. The existing options I've found online aren't quite working for me due to the object array I am passing to the Dropdown. Any assistance or guidance on this matter would ...

sort the array based on its data type

Recently diving into typescript... I have an array that is a union of typeA[] | typeB[] but I am looking to filter based on the object's type interface TypeA { attribute1: string attribute2: string } interface TypeB { attribute3: string attri ...

AngularJS ng-model not refreshing

One of the features in my application is a Font Awesome icon picker that allows employees to easily access different icons without having to search for their codes online. However, I am facing an issue where clicking on an icon does not update the ng-mode ...

Spread an all-encompassing category across a collection

What is the method in TypeScript to "spread" a generic type across a union? type Box<T> = { content: T }; type Boxes<string | number> = Box<string> | Box<number>; (Given that we are aware of when to use Boxes versus Box) ...

Tips for validating and retrieving data from a radio button paired with an input box in reactjs

I'm diving into the world of React and facing a challenge with multiple radio buttons that have associated input fields, like in this image: https://i.stack.imgur.com/Upy3T.png Here's what I need: If a user checks a radio button with a ...

Accessing instance variables from a chained observable function in Angular 2/Typescript

Currently, I am utilizing Angular2 along with Typescript. Let's assume that there is a dummy login component and an authentication service responsible for token authentication. In one of the map functions, I intend to set the variable authenticated as ...

An error occurred while trying to load the configuration "next/core-web-vitals" for extension

If you're embarking on a new project using NextJs and TypeScript, chances are you may encounter the following error: Failed to load config "next/core-web-vitals" to extend from. Wondering how to resolve this issue? ...

Here is a way to retrieve the name of a ref object stored in an array using Vue.js 3 and Typescript

I have a Form, with various fields that I want to get the value of using v-model and assign them to ref objects. In order to populate my FormData object with this data, I require both the name and the value of the ref objects. Unfortunately, I am struggli ...

Tips for incorporating Angular2 into Eclipse using TypeScript

Recently, I delved into the world of Angular 2 and noticed that TypeScript is highly recommended over JavaScript. Intrigued by this recommendation, I decided to make the switch as well. I came across a helpful guide for setting up everything in Eclipse - f ...

Beware of potential issues with FontAwesomeIcon when incorporating it into a Typescript file

I'm currently working with NextJS and Typescript. I encountered an issue when trying to import FontAwesomeIcon like this <FontAwesomeIcon icon={faCheck as any} /> as it triggered a warning in the console stating "Warning: FontAwesomeIcon: Suppor ...

Using ES6 import with the 'request' npm module: A Step-by-Step Guide

When updating TypeScript code to ES6 (which runs in the browser and Node server, with a goal of tree-shaking the browser bundle), I am attempting to replace all instances of require with import. However, I encountered an issue... import * as request from ...

Combining Rxjs map and filter to extract countries and their corresponding states from a JSON dataset

I have a unique dataset in JSON format that includes information about countries and states. For example: { "countries": [ { "id": 1, "name": "United States" }, { "id": 2, "name": "India" }], "states": [ { ...