javascriptpuppeteerjest-puppeteer

Getting custom element using puppeteer and then do click action


I've created a custom attribute called data-testId and I am trying to reach to using puppeteer and then do a click action, but for some reason, I'm unable to get this element and facing with errors. I've tried these 2 options:

const element = await page.$('[data-testId="testid-button-refresh"]');
await page.click(element, { clickCount: 1 });

and this:

const refreshButton = await page.evaluateHandle(() => {
return document.querySelector('[data-testId=testid-button-refresh]').value;
});
await page.click(element, { clickCount: 1 });

On them both I am getting this error:

JSHandles can be evaluated only in the context they were created!

What I am doing wrong? and what does it means this error?


Solution

  • With element you've created an ElementHandle which can be clicked with elementHandle.click and not with page.click.

    This should work:

    const element = await page.$('[data-testId="testid-button-refresh"]') // this is an ElementHandle
    await element.click({ clickCount: 1 })
    

    Or you can still use page.click, but to keep the click in the same context you should use the selector, and not the ElementHandle as the first argument:

    await page.click('[data-testId="testid-button-refresh"]', { clickCount: 1 })