Skip to content

Instantly share code, notes, and snippets.

@yannbf
Created March 7, 2025 17:03
Show Gist options
  • Save yannbf/d3f53f5ff19580b238f2dfa396d28a12 to your computer and use it in GitHub Desktop.
Save yannbf/d3f53f5ff19580b238f2dfa396d28a12 to your computer and use it in GitHub Desktop.
CDP-driven user events in Storybook
export const Default: Story = {
tags: ['real-events'],
play: async ({ realEvent, canvas }) => {
const button = await canvas.findByRole('button')
// realEvent is now available during tests in Vitest browser mode
await realEvent.hover(button)
await expect(button).toHaveStyle({
backgroundColor: '#F5F6F7',
})
},
}
import type { Preview } from '@storybook/react'
const preview: Preview = {
beforeEach: async function realEventsEnhancer(context) {
// Replace userEvent API when running in Vitest browser mode
// @ts-ignore
if (context.tags.includes('real-events') && globalThis.__vitest_browser__) {
const vitest = await import('@vitest/browser/context');
context.realEvent = vitest.userEvent.setup();
} else {
// optional: Either provide a fallback implementation which uses userEvent coming from '@storybook/test'
// or render a warning so the story is clearly marked as not supporting real events like
// document.body.innerHTML = 'WARNING! This story needs CDP and therefore is not supported here. Run it in the CLI instead';
}
},
}
// Type module augmentation in order to get type safety and autocompletion
declare module 'storybook/internal/csf' {
interface StoryContext {
realEvent: import('@vitest/browser/context').UserEvent
}
}
export default preview
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment