How to validate if a custom event was triggered in Playwright?

59 Views Asked by At

I have a scenario where in after clicking a certain element, a custom event should be triggered. The waitForEvent only accepts default events and I've found this thread, but without any example.

Is there a reference in Playwright regarding validating on custom events?

1

There are 1 best solutions below

0
Mike Stop Continues On

yTo accomplish this, you'll probably have to lean on code that you evaluate inside the browser. I would do something like the following:

const elementThatEmits = page.locator('#el');

// add listener for custom event
await elementThatEmits.evaluate((el) => {
  // evaluate runs code inside the browser
  el.addEventListener('custom-event', (e) => {
    window.EVENT_EMITTED = true;
  });
});

// await custom event
const res = await page.waitForFunction(() => {
  // executed in browser
  // will return when value is truth OR when timeout occurs
  return window.EVENT_EMITTED;
}, {timeout: 1000 * 60);

// `true` if successful
const val = await res.jsonValue();

I hope this points you in the right direction.