Puppeteer: initiating a click on a button within a shadow DOM root element

I'm experiencing challenges with performing actions on elements within a shadow root in my testing environment. For example, let's consider a web component called <my-component /> that includes a button:

<input id="my-button" type="submit" />

When using the Chrome console, I can successfully perform the following:

document.getElementsByTagName('my-component')[0].shadowRoot.querySelector('#my-button').click()

However, I am encountering difficulties achieving the same result with Puppeteer.

  it('should click the button', async () => {
    await page.goto(`https://localhost:${port}`, {
      waitUntil: ['networkidle0', 'load'],
    });

    await page.$eval('my-component', (el: Element) => {
      el.shadowRoot.querySelector('#my-button').click();
    });
  });

Upon clicking the button, an HTTP request should be triggered to retrieve data from my server, which I intend to assert against in the DOM. Unfortunately, the request is not being sent. Any suggestions on how to resolve this issue?

Answer №1

The solution to this problem can be found using P selectors in Puppetteer.

For this scenario, you can utilize

page.click('>>> #my-button')
. The >>> allows you to target elements within shadowRoots.

Although this issue is from some time ago, I recently encountered it and noticed that it still appears in search results.

Answer №2

As stated in a response by the Puppeteer Team, the recommended approach is to utilize JS path:

In the latest Chrome version (Chrome 88), a new option called "Copy JS Path" has been added alongside the existing "Copy Selector" feature:

https://i.sstatic.net/PsyOG.png

Here's an example demonstrating the use of JS path:

    it('should interact with the element', async () => {
      await page.goto(`https://example.com`, {
        waitUntil: ['networkidle0', 'load'],
      });
    
      const element = await (await page.evaluateHandle(`<JS-path-here>`)).asElement();
      // Perform desired actions on the element
    });

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

React is throwing an error stating that ref.current.contains is not a valid function

I created a dropdown toggle feature in my React application that is functioning perfectly. However, I encountered an error when I attempted to close the dropdown by clicking outside of the menu. To address this issue, I utilized a reference to locate the ...

In TypeScript, use a type assertion to determine if my object is empty and does not contain any keys defined in the interface

As I review my code, I realize that I have defined an interface as follows: interface User { name: string, age: number } I also have a function written like this: function test(user: User): void { } In addition, I have created an empty objec ...

Form Controller Indicates Missing Data

Issue Resolved I've encountered an issue with my form controller's values not populating when I submit the form - they remain as empty strings. My suspicion is that there might be an error on the HTML side. Here is the register.component.ts file ...

Leverage one Injectable service within another Injectable service in Angular 5

I am facing difficulties in utilizing an Injectable service within another Injectable service in Angular 5. Below is my crudService.ts file: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; ...

How to Include HttpClient in an Angular Service

Looking for a service that utilizes http requests? import { Injectable } from '@angular/core'; import { Observable, of } from 'rxjs'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root&a ...

Exploring the wonders of mocha in NYC alongside the magic of source

Trying to understand why this approach isn't yielding the desired results. The task involves developing TypeScript code in files located within the src and tests directories. These files are of types *.ts and *.spec.ts. The transpilation of both sou ...

Highcharts encounters issues with dateRange values disappearing after a refresh in older versions of IE (9 and below) and Chrome

const newCurrentIndex = findIndexForCounter(currentPCData.CounterID, currentPCData.NetworkID); if (currentIndex === newCurrentIndex) { $.each(model.Data, (j, point) => { ...

The elixir-typescript compilation process encountered an error and was unable to complete

I am currently working on integrating Angular2 with Laravel 5.2 and facing an issue with configuring gulp to compile typescript files. Below is a snippet from my package.json file: { "private": true, "scripts": { "prod": "gulp --production", ...

A guide to showcasing a series of strings in a react element

My aim is to present an array of strings on distinct lines within my React component by utilizing the following code: <div> {this.props.notifications.join('\n')} </div> Nonetheless, it appears that this a ...

There seems to be a compatibility issue between Angular 16 and Bootstrap 5 styling

In my angular.json, I have defined my styles in the following way: "styles": [ { "input": "node_modules/bootstrap/dist/css/bootstrap.min.css", "bundleName": "ltrCSS" }, { "input": "node_mod ...

Tips for getting Angular's HttpClient to return an object rather than a string?

How can I make HttpClient return the data in JSON Object format? The Angular documentation states that HttpClient should automatically parse returned JSON data as an object. However, in my project, it only returns the data as a string. Although using JSO ...

Typescript error code TS7053 occurs when an element is detected to have an implicit 'any' type due to an expression of a different type

I encountered an issue with the provided example. I'm uncertain about how to resolve it. Your assistance would be greatly appreciated. type TestValue = { value: string; }; type FirstTest = { type: 'text'; text: TestValue[]; }; typ ...

What is preventing me from dynamically generating a property?

As someone who is new to TypeScript, I have a question regarding defining properties. In JavaScript, we can define a property dynamically like this: class Rectangle { constructor(height, width) { this.height = height; this.width = width; } } ...

Steps for simulating a Pubsub.js event in a Jest test for a React.js component

In a react application, I have implemented internationalization using the react-intl library. The language can be changed in different components triggering an event, which is handled by the pubsub-js library. This event is subscribed to in my central App ...

Is it possible for a function to output an Interface within Typescript?

I'm new to typescript and wondering if it's possible to create a function that returns the interface for variable declarations. If so, how can this be accomplished? An example use case (which may not work) could look like this: let someVar: desir ...

Substitute all properties of a specific type with a predetermined value in Typescript using recursive substitution

If we consider the given type structure: type Person = { name: string age: number experience: { length: number title: string } } Can we create a type like this: type FieldsOfPerson = { name: true age: true experience: { length: t ...

determining the data type based on the function parameter even when a specific type parameter is provided

Consider this example: type UpdateFieldValue<T extends Record<string, unknown>> = (key: keyof T, value: SomeType) => void The goal is to have SomeType represent the value type of the property (key) within object T, with key being provided t ...

Verify whether the mat-dialog is currently displayed

Purpose: To trigger a dialog on page load only if it hasn't already been opened. The dialog component is separate from the current page. Issue: The dialog is opening twice. I attempted to troubleshoot by referencing StackOverflow articles like Angul ...

How to make an input blur in Angular 2 when a button is clicked?

Is there a way to blur an input field by pressing the return button on a mobile native keyboard? Here is an example: <input type="text" #search> this.search.blur() //-- unfocus and hide keyboard ...

Arranging JavaScript object by object properties (name)

Can anyone assist me with my training? I am currently learning JavaScript (Js) and TypeScript (Ts) by working with an external public API. After successfully fetching and displaying my data, I now want to implement sorting functionality. My goal is to sor ...