Design-to-Code Handshake: Storybook-to-Cypress Automation
This design outlines a scalable, automated pipeline called StoryShake, where Storybook stories serve as the single source of truth for UI components and pages. From these stories, we auto-generate:
- Cypress specs (component + E2E tests with interactions).
- Visual snapshots (via Percy or Chromatic integration in Cypress).
- Accessibility audits (via axe-core in Cypress).
Core Principles
- Design-to-Code Handoff: Designers build/review/approve stories in Figma → Storybook (via plugins like Builder.io or Anima). Developers write minimal code; automation handles tests.
- Single Source of Truth: Stories define args, states, interactions (via
play()), and test metadata.
- Zero Manual Test Writing: A CLI generator parses stories and emits Cypress files.
- Git-Friendly: Generated files are committed; diffs highlight test changes.
- CI/CD Integration: Runs in pre-commit, PR builds, and release pipelines.
- Coverage: Component testing (mount isolated) + E2E (visit app pages if stories represent pages).
Prerequisites
- Storybook 7+ (with
@storybook/test for interactions).
- Cypress 13+ (with component testing enabled).
- Node.js 18+.
- Addons/Tools:
| Tool | Purpose | Install |
|---|
@storybook/addon-interactions | Story play() functions | npx storybook@latest init |
cypress-axe | A11y audits | npm i -D cypress-axe |
@percy/cypress (or Chromatic) | Visual snaps | npm i -D @percy/cypress |
@storybook/test-runner | Baseline interaction tests | Optional fallback |
| Chromatic (free tier) | Storybook visual/a11y review | npx chromatic --project-token=... |
Storybook Story Conventions
Stories must follow this structured format for auto-generation (enforced via ESLint/Prettier).
// Button.stories.tsx (Component Example)
import type { Meta, StoryObj } from '@storybook/react';
import { Button } from './Button';
import { userEvent, waitFor, within } from '@storybook/test';
const meta: Meta<typeof Button> = {
component: Button,
parameters: {
// Handshake metadata
tests: {
viewport: 'mobile', // optional: 'mobile', 'desktop', 'full'
tags: ['critical', 'a11y-high'], // for filtering
assertions: ['visible', 'accessible'], // auto-add cy assertions
},
},
};
export default meta;
type Story = StoryObj<typeof Button>;
export const Primary: Story = {
args: { label: 'Click Me', variant: 'primary' },
play: async ({ canvasElement }) => {
// Interactions become Cypress steps
const canvas = within(canvasElement);
await userEvent.click(canvas.getByRole('button'));
await waitFor(() => expect(canvas.getByText('Clicked!')).toBeVisible());
},
};
// Page Story Example (for E2E)
export const LoginPage: Story = {
parameters: {
tests: { type: 'e2e' }, // Generates visit('/login') instead of mount
chromatic: { disableSnapshot: false }
},
play: async ({ canvasElement }) => {
// Page interactions
await userEvent.type(within(canvasElement).getByLabelText('Email'), 'user@test.com');
// ...
},
};
play(): Defines interactions (auto-translated to Cypress).
parameters.tests: Custom metadata for customization.
Generator CLI: storyshake generate
A Node.js script (bin/storyshake.js) parses *.stories.tsx files and generates Cypress specs.
Installation & Setup
npm i -D tsx glob babel-parser @babel/traverse @babel/types @storybook/csf
npx tsx bin/storyshake.js --generate
Generator Logic (Pseudocode)
// bin/storyshake.js
import fs from 'fs';
import path from 'path';
import glob from 'glob';
import * as parser from '@babel/parser';
import traverse from '@babel/traverse';
import generate from '@babel/generator';
const generateCypressSpec = (story) => {
const { title, name, args, play, parameters } = story;
const componentPath = extractComponentImport(story); // e.g., './Button'
const isE2E = parameters?.tests?.type === 'e2e';
const viewport = parameters?.tests?.viewport || 'desktop';
let spec = `
import { ${name} } from '${componentPath}';
import { ${isE2E ? '' : 'mount'} } from 'cypress/storybook';
import 'cypress-axe';
import '@percy/cypress';
import '@testing-library/cypress'; // for queries
describe('${title}', () => {
it('${name}', { viewportWidth: ${viewport === 'mobile' ? 375 : 1280} }, () => {
${isE2E ? `cy.visit('/${title.toLowerCase().replace(/\s/g, '-') }');` : `cy.mount(<${name} {...${JSON.stringify(args)}} />);`}
// Auto-inject a11y
cy.injectAxe();
// Interactions from play() (parsed and translated)
${translatePlayToCypress(play.code)} // e.g., cy.get('[data-testid=button]').click();
// Auto-assertions
${parameters.tests.assertions.includes('visible') ? 'cy.get('body').should("be.visible");' : ''}
// Visual snapshot
cy.percySnapshot('${name}');
// A11y audit
cy.checkA11y();
});
});
`;
return spec;
};
glob('src/**/*.stories.@(js|ts|jsx|tsx)', (err, files) => {
files.forEach(file => {
const stories = parseCsfFile(file); // Use Storybook CSF tools
stories.stories.forEach(story => {
const specPath = path.join('cypress/component/generated', `${story.title.replace(/\//g, '__')}.cy.ts`);
fs.writeFileSync(specPath, generateCypressSpec(story));
});
});
});
- Parsing: Use
@storybook/csf-tools or Babel to extract stories/exports/play.
- Translation: Map Storybook
userEvent.click → cy.click(), expect → cy.should(), etc.
- Outputs:
| Generated File | Example Path | Tests |
|---|
| Cypress Spec | cypress/component/generated/Button__Primary.cy.ts | Mount + play + snap + a11y |
| Snaps | Percy/Chromatic dashboard | Auto-captured |
| Audit Report | cypress/reports/a11y.json (via axe) | Violations logged |
Example Generated Cypress Spec
// cypress/component/generated/Button__Primary.cy.ts
import { Primary } from '../../../src/stories/Button.stories';
import 'cypress-axe';
import '@percy/cypress';
describe('Button', () => {
it('Primary', () => {
cy.mount(<Button label="Click Me" variant="primary" />);
cy.getByRole('button').click();
cy.contains('Clicked!').should('be.visible');
cy.injectAxe();
cy.percySnapshot('Button Primary');
cy.checkA11y();
});
});
Workflow & CI/CD Integration
Design (Figma) → Storybook Stories → storyshake generate → Cypress Specs → CI Tests
-
Local Dev:
npm run storybook # Review/approve stories
npx storyshake generate # Regenerate tests
npm run cypress:component --spec "cypress/component/generated/*"
-
Pre-Commit Hook (husky):
{ "hooks": { "pre-commit": "storyshake generate && git add cypress/component/generated/" } }
-
GitHub Actions CI (.github/workflows/storyshake.yml):
name: StoryShake
on: [pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm ci
- run: npx storybook build # Build for static analysis
- run: npx storyshake generate
- run: npx chromatic # Visual + a11y on stories
- run: npx percy exec -- npm run cypress:run:component # Generated specs + snaps
- run: npx cypress run:component --reporter mocha-junit # E2E if flagged
-
Design Review Gate:
- Chromatic PR comments: Approve visuals/a11y → Merge → Auto-generate tests.
Benefits & Extensibility
- Time Savings: 80% less test boilerplate.
- Consistency: Stories = Tests (no drift).
- Scalability: 1000+ stories → 1000+ tests in seconds.
- Extends To: Playwright (swap generator), Vitest (unit from args), Figma plugins (import designs as stories).
- Edge Cases:
| Case | Handling |
|---|
| Async play | cy.wait() injection |
| Variants | One spec per story export |
| Docs-only | Skip via parameters.tests.skip |
| Custom assertions | parameters.tests.customCode |
Limitations & Next Steps
- Parsing complex
play() requires robust translation (start with simple userEvent).
- Real-time sync: Watch mode via
chokidar.
- Ship as NPM:
npx storyshake@latest init.
This handshake ensures designs flow to bulletproof code with zero manual testing overhead. Fork the prototype repo to pilot!