The user wants a "component contract testing framework."
The framework needs to validate three specific aspects of UI components:
- Slot usage: Are named slots being filled correctly?
- Event semantics: Are events emitting the correct data types and structures?
- Theming hooks: Are CSS variables or theming APIs being respected and applied correctly?
The scale is "50+ consuming teams," implying a need for:
- Scalability: Can't run everything in one giant test suite.
- Isolation: Team A shouldn't break Team B's tests easily.
- Reporting: Need to know which team is breaking which contract.
- Automation: Needs to be part of CI/CD.
- Standards/Documentation: Teams need to know what the contracts are.
High-Level Architecture:
- The Schema (The Contract): We need a way to define what a component should look like. JSON Schema or TypeScript definitions are good candidates.
- The Runner (The Validator): A tool to render the component and check the schema. Tools like Playwright, Cypress, or Jest/Testing Library fit here.
- The Registry: Where contracts live. A shared package or a service.
- The Consumer: How other teams use this.
Detailed Breakdown by Requirement:
-
Slot Usage:
- Problem: Components often accept
children or specific named slots (e.g., header, footer). A consuming team might put a block-level element in an inline slot, or miss a required slot.
- Solution: Visual regression testing is too brittle for logic. We need structural testing. We can use the DOM API to check
slot.assignedNodes(). Or, if using React (likely), we can enforce prop types or use unit tests to check the rendered tree structure. Let's stick to a DOM-based approach for framework agnosticism.
- Approach: Define a schema like
{ slots: { header: { required: true, allowedTags: ['h1', 'h2'] } } }.
-
Event Semantics:
- Problem: A component emits
onClick, but does it pass a native Event or a custom object? Is onSubmit preventing default?
- Solution: Programmatic interaction. We need to click/submit and listen to the emitted event.
- Approach: Contract defines
{ events: { 'change': { payload: { value: 'string' } } } }. The test harness triggers the event and asserts the detail or the event object structure.
-
Theming Hooks:
- Problem: Components should use specific CSS variables (e.g.,
--primary-color) or specific class names/hooks (e.g., data-theme="dark").
- Solution: Computed style inspection.
- Approach: Contract defines
{ theme: { variables: ['--bg-color'] } }. The test renders the component and checks getComputedStyle(element).getPropertyValue('--bg-color').
Scaling to 50+ Teams:
- Distributed Testing: Each team should run contract tests against their usage of the shared component library.
- Centralized Governance: The core UI platform team maintains the "Contract Linter" and the definitions.
- Pipeline Integration: GitHub Actions/GitLab CI step.
- Versioning: Contracts must be versioned with the component library.
Designing the Solution Structure:
- Core Concept:
ContractDefinition (JSON/TS).
- Test Harness: A helper function
validateContract(Component, Contract).
- Visual/Reporting: A dashboard (optional but recommended) or standard JUnit output.
Drafting the Framework Code (Mental Sandbox):
- Language: TypeScript is best for this.
- Test Runner: Playwright is robust for cross-browser and handles shadow DOM (slots) well.
- Schema: Zod or JSON Schema.
Refining the Slot Validation:
Shadow DOM makes this tricky. We need to pierce the shadow root.
If React (no shadow DOM usually), standard DOM queries work.
Let's assume a generic DOM environment for maximum applicability.
Refining Event Semantics:
Need a way to "mock" or "spy" on events. The test harness needs to attach listeners.
Refining Theming:
Need to render within a specific context (a ThemeProvider) to see if variables resolve correctly.
Structuring the Response:
- Architecture Overview: Explain the separation of Definition, Validation, and Reporting.
- The Schema (The "What"): Show how to define a contract.
- The Engine (The "How"): The core testing library code.
- The Workflow (The "Process"): How teams actually use this in CI.
- Governance: How to manage 50+ teams (versioning, breaking changes).
Self-Correction during drafting:
Initial thought: Just write Jest tests.
Correction: Jest implies unit tests. Contract testing often requires realistic rendering. Let's suggest a custom runner based on a browser automation tool (Playwright/Puppeteer) or a specialized Storybook addon, but a generic Node-based test runner is more flexible for CI pipelines. Let's stick to a generic framework-agnostic approach using a "Contract Tester" library.
Let's build a conceptual implementation called "PactUI".
Key Features to Highlight:
- Schema-Driven: Contracts are data.
- Framework Agnostic: Tests the DOM, not the framework (React/Vue/etc.).
- Context-Aware: Tests theming by wrapping in context.
Writing the Code:
I will provide a TypeScript implementation structure.
types.ts: Interfaces for Contracts.
validator.ts: The logic to check slots, events, styles.
runner.ts: Orchestrating the tests.
Addressing the "50+ Teams" aspect:
This is organizational as much as technical.
- Monorepo/Polyrepo support: The contracts need to be an NPM package.
- Opt-in/Opt-out: Granular controls.
- Reporting: Needs to output JSON for aggregation.
Final Polish:
Make sure the event semantic part includes type checking (using Zod or similar runtime types). Make sure theming checks computed styles, not just inline styles.
Let's construct the response.
- Title: The "Interface Integrity Framework" (IIF).
- Section 1: The Contract Schema.
- Section 2: The Validation Engine (Code).
- Section 3: CI/CD Strategy.
(Self-Correction on Slot validation): It's hard to validate "Slot usage" from the inside of a component without knowing what's passed in. Actually, the prompt says "validates slot usage... across consuming teams". This implies the consumer runs the test, or the component tests against valid consumer inputs.
Wait, usually contract testing is: Provider (Component Lib) vs Consumer (App).
The prompt implies the Component Lib needs to ensure that if a team uses the component, the slots/events/themes work as expected.
Or, it implies we are linting the consuming team's code to ensure they are using the slots correctly?
"Validates slot usage... across 50+ consuming teams" -> This sounds like an auditing tool.
Let's aim for a Consumer-Driven Contract (like Pact) or Provider-Verification approach.
Actually, the most practical interpretation for UI components is: The UI Platform team defines the contract. The consuming teams run a CI step that says "Here is how I use Button, is this valid against the latest Button contract?".
Alternative interpretation: The UI Platform team has a suite of tests that ensures the component adheres to the expected behavior (The Contract) so that 50+ teams can rely on it.
"Validates slot usage... across 50+ consuming teams" suggests checking the integration.
Let's go with: A federated testing suite. The Core Library exposes Contracts. Consuming apps include a "Contract Test Runner" in their CI that validates their usage of the components against the library's contracts.
Plan:
- Core Package (
@org/ui-contracts): Defines the Zod schemas/Types.
- Testing Library (
@org/ui-validator): The engine.
- Usage: Consumers write a simple test file mapping their usage to the contract.
Let's refine the "Theming" part.
Check: Does Button use var(--btn-bg)?
This is a Provider test.
Check: Does App provide --btn-bg?
This is a Consumer test.
The prompt asks for validation across teams. This suggests checking that teams are implementing themes correctly or that the components work within the teams' themes. I will focus on validating that the components render correctly within the specific theming context of the consuming application.
Let's start generating.
To address the challenge of governing a UI component library across 50+ teams, we need a Distributed Contract Testing Framework.
Unlike traditional unit tests (which check implementation) or end-to-end tests (which check user flows), this framework focuses on Interface Compliance. It ensures that consuming teams are using components correctly (inputs/slots) and that components are communicating correctly (events/context) regardless of the specific business logic.
Here is the architectural blueprint and implementation strategy for the "Interface Integrity Framework" (IIF).
1. The Architecture
The framework consists of three pillars:
- The Schema (The Contract): A machine-readable definition of Slots, Events, and Theme hooks (JSON Schema/YAML).
- The Linter (Static Analysis): Validates compile-time usage (Slots and Prop types).
- The Runtime Validator (Browser): Validates runtime behavior (Event payloads and CSS Variable injection).
2. The Contract Definition (The Schema)
We define a standard *.ui-contract.yaml file that lives alongside the component code. This acts as the "Source of Truth" for the 50+ teams.
# Button.ui-contract.yaml
component: Button
version: 2.1.0
slots:
- name: leadingIcon
required: false
allowedTypes: ['SVG', 'IconComponent']
- name: default
required: true
validation: "typeof content === 'string' && content.length > 0"
events:
- name: onClick
payloadSchema:
type: object
properties:
id: { type: string }
timestamp: { type: number }
required: [id]
- name: onHover
description: "Fires strictly on mouseenter, not focus"
theming:
hooks:
- name: --button-primary-bg
type: color
- name: --button-border-radius
type: dimension
modes: [light, dark, high-contrast]
3. The Engine (TypeScript Implementation)
We need a test runner utility that consuming teams can import into their own unit/integration test suites. This validates their specific usage against the contract.
File: contract-tester.ts
This utility uses MutationObserver for slots, generic event spies, and CSS inspection APIs.
import { z } from 'zod'; // Using Zod for runtime schema validation
type ContractSpec = {
slots: Array<{ name: string; required: boolean; validation?: string }>;
events: Array<{ name: string; payloadSchema: object }>;
theming: { hooks: string[] };
};
export class ContractTester {
private component: HTMLElement;
private spec: ContractSpec;
constructor(component: HTMLElement, spec: ContractSpec) {
this.component = component;
this.spec = spec;
}
/**
* 1. Validates Slot Usage
* Checks if required slots are filled and if the DOM structure respects the contract.
*/
public validateSlots() {
console.log(`Validating slots for ${this.component.tagName}...`);
// Using light DOM or shadow DOM traversal
const assignedNodes = (this.component as any).shadowRoot
? (this.component as any).assignedNodes()
: this.component.childNodes;
this.spec.slots.forEach(slot => {
// Check required slots
if (slot.required) {
const hasContent = assignedNodes.length > 0 || this.component.innerHTML.length > 0;
if (!hasContent) {
throw new Error(`Contract Violation: Required slot "${slot.name}" is empty.`);
}
}
// Check validation rules (evaluated in browser context)
if (slot.validation) {
try {
// In a real scenario, use a safe evaluator, not Function constructor
const isValid = new Function('content', `return ${slot.validation}`)(this.component.innerHTML);
if (!isValid) {
console.warn(`Contract Warning: Slot "${slot.name}" failed semantic validation rule.`);
}
} catch (e) {
console.error(`Validation logic error for slot ${slot.name}`);
}
}
});
return this;
}
/**
* 2. Validates Event Semantics
* Ensures events emit the correct data structure.
*/
public async validateEvent(eventName: string, triggerFn: () => void) {
const eventSpec = this.spec.events.find(e => e.name === eventName);
if (!eventSpec) throw new Error(`Unknown event contract: ${eventName}`);
const schema = z.object(eventSpec.payloadSchema as any);
return new Promise((resolve, reject) => {
const listener = (e: CustomEvent) => {
try {
// Validate payload structure
schema.parse(e.detail);
console.log(`✅ Event ${eventName} payload valid.`);
resolve(true);
} catch (err) {
console.error(`❌ Contract Violation: Event "${eventName}" emitted invalid payload.`);
console.error(err);
reject(err);
} finally {
this.component.removeEventListener(eventName, listener);
}
};
this.component.addEventListener(eventName, listener);
triggerFn(); // Trigger the user action (e.g., component.click())
});
}
/**
* 3. Validates Theming Hooks
* Ensures the component reacts to CSS Custom Properties.
*/
public validateTheming(mode: 'light' | 'dark') {
const expectedVars = this.spec.theming.hooks.map(h => h.name);
// Force a style recalculation
const styles = window.getComputedStyle(this.component);
let passed = true;
expectedVars.forEach(cssVar => {
// Check if the component actually uses this variable
// Note: Browsers don't easily expose 'used' css vars via API,
// so we check computed style differences or inline style checks.
// Heuristic: Verify the variable is defined in the theme context
const value = styles.getPropertyValue(cssVar);
if (!value) {
console.warn(`Theme Hook Missing: ${cssVar} is not defined in the current context for ${this.component.tagName}`);
passed = false;
}
});
if (!passed) throw new Error("Theming contract incomplete.");
return this;
}
}
4. The Consumer Integration (CI/CD Workflow)
For 50+ teams, we cannot rely on manual testing. We package the ContractTester as an NPM package (@org/ui-contracts) and require teams to run a specific script in their CI pipeline.
Usage in a Consuming Team's Repo (Jest/Playwright)
Team Alpha is using the Button component in their PaymentForm.
// payment-form.contract.test.ts
import { ButtonContract } from '@org/ui-contracts/definitions';
import { ContractTester } from '@org/ui-contracts/tester';
import { render } from '@testing-library/react'; // Or Vue/Svelte/Angular
import { PaymentForm } from './PaymentForm';
describe('PaymentForm Component Contract Compliance', () => {
let container: HTMLElement;
beforeEach(() => {
container = render(<PaymentForm />).container;
});
test('Button Slot Usage is compliant', () => {
// Find the component instance
const buttonNode = container.querySelector('org-button');
// Run the automated test
new ContractTester(buttonNode, ButtonContract)
.validateSlots();
// Fails if the button has no text content (violates 'default' slot requirement)
});
test('Button Event Semantics are compliant', async () => {
const buttonNode = container.querySelector('org-button');
const tester = new ContractTester(buttonNode, ButtonContract);
// Simulate a click and validate the resulting event payload
await tester.validateEvent('onClick', () => {
buttonNode.click();
});
});
});
5. Governance & Scalability Strategy
Managing this across 50 teams requires a specific operational workflow to prevent version drift.
A. Versioning Strategy
- Semantic Versioning of Contracts: The contract definitions are versioned separately from the component library code.
- Deprecation Policy: If
onClick payload changes, a new Contract version (v3) is released. Teams on v2 see warnings but their builds don't break immediately.
B. The "Contract Gateway" (CI Plugin)
Instead of asking teams to write tests manually (which leads to coverage gaps), build a CLI tool.
npx @org/ui-contracts scan ./src
How it works:
- Static Analysis (AST): It parses the consuming team's codebase. It looks for
<Button>. It checks if it has children (Slots). It checks if onClick is passed a function.
- Reporting: It outputs a
compliance-report.json.
- Enforcement: In the CI pipeline (GitHub Actions/GitLab CI), if the compliance score drops below 95%, the PR is blocked.
C. Handling Theming at Scale
To validate theming hooks without visual regression:
- Theme Context Injection: The framework injects a "Test Theme" (mock values like
#ff0000 for all colors).
- DOM Snapshot: It verifies that the Component's computed style reflects
#ff0000.
- Result: If the component hardcoded a color (e.g.,
color: blue) instead of using the hook (e.g., color: var(--primary-bg)), the test fails. This ensures all teams adhere to the Design System tokens.
6. Summary of Validation Layers
| Layer | Validation Type | Tooling Approach | Consumer Impact |
|---|
| Slots | Structural | AST Analysis (Static) + DOM Query (Runtime) | Build Failure if required slots missing. |
| Events | Behavioral | Runtime Spy (Jest/Playwright) | Test Failure if payload schema mismatches. |
| Theming | Visual/Styling | CSS Variable Injection & Computed Style Check | Build Failure if hardcoded values detected. |
This framework ensures that while teams have autonomy in how they build features, they strictly adhere to the interface defined by the central UI platform team.