Last active
July 5, 2025 13:17
-
-
Save fgeierst/a8b8023a00e59c1a1a072542798b84d4 to your computer and use it in GitHub Desktop.
Playwright Event Testing Pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://github.com/microsoft/fluentui/blob/master/packages/web-components/src/dropdown/dropdown.spec.ts