typescriptjestjspuppeteerweb-componentweb-component-tester

puppeteer: clicking button in shadowroot


I'm having difficulties with actions on elements in shadowroot in my test context. Lets say I have a web component <my-component /> and it contains a button <input id="my-button" type="submit" />

From console in chrome, I can do the following:

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

Im struggling doing the same 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();
    });
  });

Clicking the button should fire an http request to my server that retrieves some data which I then want to assert on in the dom. The request never fires. Suggestions?


Solution

  • According to this comment from the Puppeteer Team the right way is to use JS path:

    In Chrome 72 (current Canary) we introduced a new option - "Copy JS Path", located right next to the "Copy Selector" option:

    aaa

    Example using JS path:

        it('should click the button', async () => {
          await page.goto(`https://localhost:${port}`, {
            waitUntil: ['networkidle0', 'load'],
          });
        
          const button = await (await page.evaluateHandle(`<JS-path-here>`)).asElement();
          button.click();
        });