Skip to content

Instantly share code, notes, and snippets.

@fgeierst
Last active July 5, 2025 13:17
Show Gist options
  • Save fgeierst/a8b8023a00e59c1a1a072542798b84d4 to your computer and use it in GitHub Desktop.
Save fgeierst/a8b8023a00e59c1a1a072542798b84d4 to your computer and use it in GitHub Desktop.
Playwright Event Testing Pattern
import { expect, test } from '@playwright/test';
test('should emit a custom event on interaction', async ({ page }) => {
// Assume 'my-component' is a web component that emits a 'custom-event'
await page.setContent(`
<button id="myButton">Click Me</button>
<my-component></my-component>
`);
const myComponent = page.locator('my-component');
const myButton = page.locator('#myButton');
const [eventFired] = await Promise.all([
// Promise 1: Set up an event listener on the component in the browser context
myComponent.evaluate(
el =>
new Promise((resolve, reject) => {
// Set a timeout to fail if the event doesn't fire
const timeout = setTimeout(() => reject('custom-event was not emitted within 1000ms'), 1000);
// Listen for the 'custom-event'
el.addEventListener(
'custom-event',
() => {
clearTimeout(timeout); // Clear the timeout if the event fires
resolve('event-fired'); // Resolve the promise
},
{ once: true }, // Listen only once
);
}),
),
// Promise 2: Trigger the action that is expected to emit the event
myButton.click(), // Example: clicking a button that causes the component to emit
]);
// Assert that the event was successfully fired
expect(eventFired).toBe('event-fired');
});
@fgeierst
Copy link
Author

fgeierst commented Jul 5, 2025

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment