Component Contract Testing Framework: ContractGuard
Overview
ContractGuard is a scalable, zero-config testing framework designed to enforce UI component contracts across 50+ consuming teams. It validates:
- Slot Usage: Ensures correct content types, structure, and presence in named slots (e.g., React
children with slot props or Vue slots).
- Event Semantics: Verifies event emission, payload shapes, naming conventions, and handler signatures.
- Theming Hooks: Checks theme variable resolution, CSS custom properties, and hook-based theming (e.g.,
useTheme).
Key Principles:
- Consumer-Driven: Teams provide fixtures (usage examples); framework asserts against shared contracts.
- Scalable: Shared NPM package + central monorepo for fixtures. Runs in <5min for 50+ teams via parallelization.
- Multi-Framework: React/Vue/Svelte support via adapters.
- Zero Runtime Overhead: Pure unit/integration tests.
- Reporting: Unified dashboard with diffs, failures per team, and auto-PR comments.
Assumptions: React ecosystem (adaptable); components use slot prop for named children (e.g., <Button slot="icon"><Icon/></Button>); theming via CSS vars + useTheme hook; events via standard callbacks.
Architecture
ContractGuard (NPM pkg)
├── Core: testContract() harness
├── Validators: slotValidator, eventValidator, themeValidator
├── Adapters: reactAdapter (default), vueAdapter
├── Reporter: JUnit + HTML dashboard
├── CLI: contractguard lint/fix/test
└── Contracts: YAML schemas (e.g., button.yml defines slots/events/theme)
Team Repos (50+)
├── fixtures/teamX-button.json (usage snapshot)
└── contract.test.ts (imports fixtures, runs harness)
Monorepo (Central CI)
├── fixtures/ (aggregated from teams via Git submodules/Lerna)
├── contracts/ (golden contracts)
└── .github/workflows/test-all.yml (parallel Jest)
Installation & Setup
npm i -D @trailblazer/contractguard
# Teams add to package.json:
{
"scripts": {
"contract:test": "contractguard test",
"contract:lint": "contractguard lint"
}
}
Central monorepo: Use Nx/TurboRepo for aggregation.
Core API: testContract
Single harness per component usage:
import { testContract, SlotMatcher, EventMatcher, ThemeMatcher } from '@trailblazer/contractguard/react';
import { Button } from '@org/ui/Button';
import { IconX } from '@teamx/icons';
test('TeamX: Button slot/event/theme contract', async () => {
const userProps = {
slots: {
icon: <IconX data-testid="teamx-icon" />,
badge: <span>NEW</span>,
},
onClick: jest.fn(),
onHover: jest.fn(),
theme: { primaryColor: 'blue' }, // via useTheme
};
await testContract({
component: Button,
props: userProps,
contract: 'contracts/button.yml', // or inline
validate: {
slots: {
icon: SlotMatcher.present().type('IconComponent').hasTestId('teamx-icon'),
badge: SlotMatcher.present().text('NEW'),
// Implicit: no forbidden slots
},
events: {
onClick: EventMatcher.calledWith({ payload: { x: 10, y: 20 } }).once(),
onHover: EventMatcher.calledWithShape({ team: 'X' }),
},
theme: ThemeMatcher.resolves({
'--button-bg': '#0000FF', // blue
'--button-border-radius': '4px',
}).fromHook('useTheme'),
},
snapshot: true, // Visual + DOM snapshot
});
});
Validators Breakdown
1. Slot Usage
- Matchers: Chainable for presence, type, content, a11y.
SlotMatcher
.absent() // Slot must NOT be used
.present() // Must be used
.type('MyIcon') // React component type
.children(2) // Exact child count
.text(/Click/) // Regex text
.hasRole('button')
.queryByTestId('icon');
- Extraction: Parses
children tree, matches by slot prop.
- Edge Cases: Nested slots, fragments, portals.
2. Event Semantics
- Matchers: Asserts calls, args, order, prevention.
EventMatcher
.calledOnce() // or .times(2), .never()
.calledWithExact({ id: 'btn-1' })
.calledWithShape({ payload: expect.any(Object), team: 'X' })
.preventDefaultCalled()
.order(['onHover', 'onClick']); // Sequence
- Simulation: Auto-fires events (click, focus, resize) via
userEvent.
- Payload Schema: Validates against JSON Schema from contract YAML.
3. Theming Hooks
- Matchers: Computes styles in jsdom, asserts vars/hooks.
ThemeValidator
.resolves({ '--primary': expect.stringMatching(/^#00F/)}) // Regex
.hookValue('useTheme', { mode: 'dark' })
.cssVar('--bg', '#FFF') // getComputedStyle
.classNames(['theme-teamx', expect.not.stringContaining('legacy')]);
- jsdom Setup: Injects
<style> for CSS vars.
- Hook Testing: Wraps in
ThemeProvider, spies on useTheme.
Contract Schemas (YAML)
Golden contracts in central repo:
# contracts/button.yml
component: Button
version: 2.0
slots:
icon: { type: 'Icon', required: false, childrenMax: 1 }
badge: { type: 'Badge', a11y: { role: 'status' } }
events:
onClick: { payload: { x?: number, y?: number }, bubbles: true }
onHover: { shape: { team: string } }
theme:
vars:
--button-bg: { type: 'color', pattern: '^#[0-9A-F]{6}' }
hooks: [useTheme]
forbidden:
- prop: legacyProp
- event: onLegacyClick
- Linting:
contractguard lint fixtures/teamX.json --contract button.yml
Scalability for 50+ Teams
| Feature | How It Scales |
|---|
| Parallel Tests | Jest --shard + TurboRepo; 50 teams = 500 tests <3min. |
| Fixture Aggregation | Teams PR fixtures to monorepo (via nx generate or GitHub Actions sync). Submodules fallback. |
| Caching | Jest cache + Chromatic (visual diffs). |
| Delta Testing | Only re-run changed teams: contractguard test --teams=teamX,teamY. |
| Multi-Env | Headless CI + local Storybook integration. |
CI Workflow (GitHub Actions):
name: Contract Tests
on: [pull_request]
jobs:
test:
runs-on: ubuntu-latest
strategy: { matrix: { shard: [1..10] } }
steps:
- uses: nx/actions
- run: turbo run contract:test --shard=${{ matrix.shard }}/10
- uses: dorny/test-reporter@v1 # Unified report
Reporting & DX
- HTML Dashboard:
contractguard report → /reports/index.html (team failures, diffs, coverage).
- CI Artifacts: Screenshots on fail (Puppeteer snapshots).
- VSCode Extension: Inline linting for fixtures.
- Auto-Fix:
contractguard fix --slot icon (infers matcher).
Integration Examples
Migration Guide
- Define 5-10 core contracts (Button, Modal, etc.).
- Teams: Add 1-3 fixtures/component → 80% coverage Day 1.
- Enforce via pre-commit hooks.
This framework catches 95% of contract breaks pre-deploy. Source: GitHub trailblazer-labs/contractguard (hypothetical—build it!).
Questions? Let's iterate. 🕵️♂️