StorybookTesting - SergeiGolos/wod-wiki GitHub Wiki
Storybook Testing
Overview
This project uses Storybook's test runner to perform interaction tests on components. The test runner uses Playwright to interact with Storybook stories to verify component functionality.
Prerequisites
- Node.js 16 or later
- npm or yarn
Installation
The Storybook test runner is already included as a development dependency. It was installed using:
npm install --save-dev @storybook/test-runner
Running Tests
- Start the Storybook development server:
npm run dev
- In a separate terminal, run the test runner:
npm run test-storybook
Writing Tests
Tests are written using the play
function in Storybook stories. The play
function receives a context object that includes utilities for interacting with the story canvas.
Example: Timer Test
The TimerTest.stories.tsx
file contains an example of an interaction test that:
- Validates a timer component is initially in the correct state
- Clicks a button to start the timer
- Waits for the timer to complete
- Verifies the timer has stopped and efforts/sets are recorded correctly
export const TimerInteractionTest: SimpleTimerStory = {
play: async ({ canvasElement, step }) => {
const canvas = within(canvasElement);
await step('Verify initial state', async () => {
// Test initial component state
});
await step('Click run button to start timer', async () => {
// Interact with the component
});
await step('Wait for timer to complete', async () => {
// Wait for async operations
});
await step('Verify effort summary', async () => {
// Validate final state
});
},
}
Key Testing Utilities
within()
: Creates a testing instance for a specific DOM elementuserEvent
: Simulates user interactions like clicks, typing, etc.waitFor()
: Waits for conditions to be trueexpect()
: Assertion function to verify conditionsstep()
: Groups test steps for better error reporting
Best Practices
- Use data-testid attributes to select elements reliably
- Break tests into logical steps using the
step()
function - Include timeouts for async operations
- Test real user interactions rather than internal implementation
- Keep stories focused on specific functionality
Troubleshooting
If tests are failing, check:
- Is Storybook running?
- Are there any console errors in the Storybook UI?
- Are the selectors (like data-testid) correctly matching DOM elements?
- For timing issues, try increasing the timeout in
waitFor()