The user wants a system where Storybook stories automatically generate three things:
Cypress specs (Functional testing)
Visual snapshots (Visual regression testing)
Accessibility audits (A11y testing)
This is a "design-to-code handshake" concept. I need to design an architecture and implementation workflow that connects these tools. Storybook acts as the single source of truth for the component's state.
Key Components:
Storybook (The Source): Needs to be the place where component states are defined.
The Bridge (Generator/Parser): Something needs to read the Storybook index (or stories) and generate code. This could be a CLI tool or a script.
Cypress (The Runner): Needs to run the generated tests.
Tools for Visuals & A11y:
Visuals: Percy, Lost Pixel, or Cypress Snapshots. Let's stick to Cypress-based tools for simplicity, like cypress-image-snapshot or generic Cypress commands interacting with a visual service.
A11y: cypress-axe or @storybook/test with axe-core. Since the prompt asks for Cypress specs to be generated, the A11y check should happen within Cypress.
The Design Challenge:
How do we go from a Storybook story (e.g., Button.stories.tsx) to a Cypress test file (e.g., Button.cy.ts) without manually writing the Cypress file every time?
Proposed Architecture:
Step 1: Instrumentation. The Storybook stories need to be strictly defined so the generator knows what to test.
Step 2: Extraction. Use Storybook's index.json (generated via sb extract or the composition API) to get a list of all stories and their IDs.
Step 3: Generation. A Node.js script iterates through the index and writes .cy.ts files based on a template.
Step 4: Execution. Cypress runs these generated files.
Detailed Workflow:
Storybook Setup:
Define stories as usual.
Use standard IDs.
The Generator (The "Handshake" Script):
It reads the Storybook metadata.
For every story:
Generate a describe block.
Generate an it block for "Visual Snapshot".
Generate an it block for "Accessibility Audit".
Generate an it block for "Interaction/Snapshot" (optional, but good for functional logic).
The Cypress Implementation:
Use cy.visit to go to the static Storybook iframe URL.
Run cy.injectAxe and cy.checkA11y.
Run visual snapshot command.
Refining the "Handshake":
The handshake implies a contract.
Contract: If a designer/developer adds a story, the tests appear automatically.
Constraint: The stories need to be exported/accessible.
Drafting the Code Structure:
Configuration: A handshake.config.js to map Storybook URL to Cypress folder.
Script:generate-tests.js.
Template: A literal string or template file for the Cypress test.
Visuals:
Let's assume a generic visual testing command like cy.compareSnapshot (from cypress-image-snapshot or similar) or just a placeholder for a service like Percy (cy.percySnapshot). Let's go with a generic cy.visualSnapshot to be tool-agnostic but descriptive.
Accessibility:cypress-axe is the standard here.
Structure of the Response:
High-Level Architecture: Diagram or flow description.
Prerequisites: What tools are needed.
The "Handshake" Script: The core code that generates the specs.
The Cypress Commands: Custom commands for A11y and Visuals.
CI/CD Integration: How to make this run in a pipeline.
Self-Correction/Refinement:
Issue: Hardcoding the URL in the generator might be brittle.
Solution: Use environment variables.
Issue: Storybook usually runs on port 6006, but in CI, it might be a static build.
Solution: The generator should point to the built static Storybook or allow a dynamic URL base.
Let's write the code.
Input: Storybook Index (JSON).
Output: Cypress Spec (TypeScript/JavaScript).
I will create a Node.js script that acts as the "Compiler" for this handshake.
Plan:
Storybook Config:main.js needs to output index.json.
Generated Output Example: Show what the file looks like.
Let's emphasize the Design-to-Code aspect. The Storybook story is the design specification in code. By automating the test generation, we close the loop.
Specific Code Snippets:
Fetching index.json.
Mapping stories to filenames.
Writing the file.
Visuals Note:
I will use a generic placeholder logic for the visual comparison to ensure the user can swap in Percy, Applitools, or native Cypress screenshotting.
A11y Note:
I will use cypress-axe logic.
Final Polish:
Make sure the tone is technical and architectural. Use formatting for readability.
(Self-Correction during drafting):
Wait, simply generating files is "handshake" enough? Maybe include a "watch" mode? No, keep it simple for the prompt: generate-on-build. The "handshake" is the mapping of the Story ID to the Test ID.
Revised Architecture Steps:
Build Storybook: Generates the static site and index.json.
Run Generator: Parses index.json, writes .cy.ts files into cypress/e2e/generated/.
Run Cypress: Executes the generated tests against the static Storybook build.
This ensures that if the Storybook build fails or is empty, no tests run (or they fail safely).
Let's proceed with this design.
This design-to-code handshake architecture treats Storybook as the Single Source of Truth. By instrumenting Storybook stories with specific metadata, we can create a "Compiler" script that automatically generates, updates, and synchronizes your End-to-End (E2E) tests, visual regression snapshots, and accessibility audits.
Here is the complete architecture and implementation strategy.
🏛️ The Architecture
The handshake consists of three phases:
The Contract (Design): Developers write Storybook stories enriched with testing metadata (play functions, interaction tests).
The Compiler (Bridge): A Node.js script extracts the Storybook Index and generates Cypress spec files.
The Execution (Code): Cypress runs the generated specs against a static build of Storybook.
mermaid
graph LR
A[Storybook Stories] -->|Metadata| B(Storybook Index JSON)
B --> C{Spec Generator Script}
C -->|Writes| D[Cypress Spec Files]
D --> E[Cypress Runner]
E --> F[Visual Snaps]
E --> G[A11y Audits]
E --> H[Interaction Checks]
1. The Contract: Enriched Storybook Stories
We use Component Story Format (CSF). To enable the handshake, we standardise on two things:
play functions: To define interaction logic inside Storybook.
Tags/Parameters: To tell the generator which tests to run.
Example Component:Button.jsxExample Story:Button.stories.jsx
This is the core logic. Instead of manually writing Cypress files, we write a script that queries the internal Storybook Index (usually available via storybook-static/index.json or the dev server).
scripts/generate-cypress-from-storybook.js
javascript
const fs = require('fs');
const path = require('path');
const axios = require('axios');
// Configuration
const STORYBOOK_URL = 'http://localhost:6006'; // Or path to static build
const CYPRESS_INTEGRATION_FOLDER = 'cypress/e2e/generated';
async function generateSpecs() {
try {
// 1. Fetch the Storybook Index
// Note: In CI, you might parse storybook-static/index.json directly
const response = await axios.get(`${STORYBOOK_URL}/stories.json`);
const storiesIndex = response.data;
if (!fs.existsSync(CYPRESS_INTEGRATION_FOLDER)) {
fs.mkdirSync(CYPRESS_INTEGRATION_FOLDER, { recursive: true });
}
// 2. Iterate over stories
Object.values(storiesIndex.stories).forEach((story) => {
// Filter logic: Only generate for stories tagged with 'test-generator'
if (!story.tags.includes('test-generator')) return;
const componentName = story.title.split('/')[1]; // e.g., 'Button'
const specFileName = `${componentName}.cy.js`;
const specFilePath = path.join(CYPRESS_INTEGRATION_FOLDER, specFileName);
// 3. Generate the Test Content
const fileContent = `
/**
* Auto-generated by Design Handshake Script
* Source: ${story.title} / ${story.name}
* DO NOT EDIT MANUALLY
*/
describe('${story.title}', () => {
const storyId = '${story.id}';
beforeEach(() => {
// Visit the static storybook iframe for isolation
cy.visit('/iframe.html?id=${story.id}&viewMode=story');
// Inject axe-core for accessibility
cy.injectAxe();
});
it('Visual Snapshot: ${story.name}', () => {
// Wait for fonts and lazy loading
cy.waitForIdle(500);
// Take snapshot using your visual plugin (e.g. Percy or cypress-image-snapshot)
// We use the Story ID as the snapshot name
cy.matchImageSnapshot(storyId);
});
it('Accessibility Audit: ${story.name}', () => {
// Run axe-core check
cy.checkA11y(null, {
rules: ${JSON.stringify(story.parameters?.a11y?.rules || [])}
}, (violations) => {
// Custom error reporting if needed
throw new Error(\`A11y violations found: \${violations.length}\`);
});
});
});
`;
// 4. Write the file
fs.writeFileSync(specFilePath, fileContent);
console.log(`Generated spec: ${specFileName}`);
});
} catch (error) {
console.error('Error generating specs:', error);
process.exit(1);
}
}
generateSpecs();
3. The Execution: Cypress Setup
To support the generated code, your cypress/support/e2e.js needs to be configured to handle the commands used in the generator (injectAxe, matchImageSnapshot, waitForIdle).
cypress/support/e2e.js
javascript
import 'cypress-axe';
import { addMatchImageSnapshotPlugin } from 'cypress-image-snapshot/plugin';
// Custom command to wait for network idle (crucial for consistent visuals)
Cypress.Commands.add('waitForIdle', (ms) => {
cy.wait(ms); // Simple implementation, can be made smarter
});
// Plugins setup (in cypress.config.js typically, but logic applies)
4. The CI/CD Pipeline (The Handshake)
This is how you enforce the loop in your deployment pipeline (e.g., GitHub Actions).
yaml
# .github/workflows/design-handshake.yml
name: Design Handshake
on: [push]
jobs:
handshake:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Install Dependencies
run: npm ci
# STEP 1: Build Storybook (The Source of Truth)
- name: Build Storybook
run: npm run build-storybook -o storybook-static
# STEP 2: Run the Generator (Create the Code)
- name: Generate Cypress Specs
run: node scripts/generate-cypress-from-storybook.js
env:
STORYBOOK_URL: file://$(pwd)/storybook-static
# STEP 3: Run Cypress (Visuals & A11y)
- name: Run Cypress Tests
uses: cypress-io/github-action@v5
with:
browser: chrome
config: baseUrl=file://$(pwd)/storybook-static
Summary of Benefits
Single Source of Truth: If a designer changes a component's state in Storybook, the play function or arguments are updated. The next CI run automatically generates a new Cypress test for that state.
Zero Boilerplate: Developers do not write Cypress spec files for basic component verification; they write Storybook stories.
Shift-Left Accessibility: A11y audits are not an afterthought; they are hard-coded into the template for every generated test.
Visual Consistency: Because the generator creates a snapshot test for every story, you are guaranteed 100% visual coverage of your component library.