This is a comprehensive request for building an Angular component library with visual regression testing. Let me break down what's needed:
Angular component library setup
Storybook configuration for Angular
Visual regression testing with either Chromatic or Puppeteer
Pixel difference threshold of 0.1%
Knobs/controls to toggle Angular directives
CI integration
I'll create a complete, production-ready solution with:
A sample Angular component library
Storybook setup with Angular
Visual regression testing using Puppeteer (more control, no external service)
CI configuration
Example components with directives
Comprehensive documentation
Let me structure this properly:
Project setup files (package.json, angular.json)
Sample components with directives
Storybook configuration
Visual regression testing script (Puppeteer)
CI/CD configuration
Testing utilities
Documentation
I'll make this complete and practical.
Angular Component Library with Visual Regression Testing
I'll build a complete production-ready solution with Storybook, Puppeteer visual regression testing, and Angular directive toggling.
1. Project Structure
code Copy code
component-library/
├── projects/
│ └── my-lib/
│ ├── src/
│ │ ├── lib/
│ │ │ ├── button/
│ │ │ ├── card/
│ │ │ └── badge/
│ │ └── public-api.ts
│ └── ng-package.json
├── .storybook/
│ ├── main.ts
│ ├── preview.ts
│ └── manager.ts
├── scripts/
│ ├── visual-regression.ts
│ └── baseline-update.ts
├── stories/
│ └── *.stories.ts
├── __visual_regression__/
│ ├── baselines/
│ ├── current/
│ └── diff/
├── .github/workflows/
│ └── visual-regression.yml
├── package.json
├── tsconfig.json
└── angular.json
2. Package Configuration
json Copy code
{
"name": "angular-component-lib-visual",
"version": "1.0.0",
"scripts": {
"ng": "ng",
"build:lib": "ng build my-lib",
"storybook": "storybook dev -p 6006",
"build:storybook": "storybook build",
"test:visual": "ts-node scripts/visual-regression.ts",
"test:visual:update": "ts-node scripts/baseline-update.ts",
"test:visual:ci": "CI=true ts-node scripts/visual-regression.ts",
"lint": "ng lint"
},
"dependencies": {
"@angular/animations": "^17.0.0",
"@angular/common": "^17.0.0",
"@angular/compiler": "^17.0.0",
"@angular/core": "^17.0.0",
"@angular/forms": "^17.0.0",
"@angular/platform-browser": "^17.0.0",
"@angular/platform-browser-dynamic": "^17.0.0",
"rxjs": "^7.8.0",
"tslib": "^2.6.0",
"zone.js": "^0.14.0"
},
"devDependencies": {
"@angular-devkit/build-angular": "^17.0.0",
"@angular/cli": "^17.0.0",
"@angular/compiler-cli": "^17.0.0",
"@storybook/angular": "^7.6.0",
"@storybook/addon-controls": "^7.6.0",
"@storybook/addon-docs": "^7.6.0",
"@storybook/addon-actions": "^7.6.0",
"@storybook/addon-viewport": "^7.6.0",
"@storybook/addon-measure": "^7.6.0",
"puppeteer": "^21.0.0",
"pixelmatch": "^5.3.0",
"pngjs": "^7.0.0",
"ts-node": "^10.9.0",
"typescript": "^5.2.0",
"sharp": "^0.33.0"
}
}
3. Sample Components
Button Component with Directives
typescript Copy code
// projects/my-lib/src/lib/button/button.component.ts
import { Component, Input, HostBinding } from '@angular/core';
import { CommonModule } from '@angular/common';
import { PulseDirective } from '../directives/pulse.directive';
import { DisabledDirective } from '../directives/disabled.directive';
@Component({
selector: 'lib-button',
standalone: true,
imports: [CommonModule, PulseDirective, DisabledDirective],
template: `
<button
[class]="'btn btn-' + variant"
[libPulse]="pulse"
[libDisabled]="disabled"
[attr.aria-label]="ariaLabel"
>
<span *ngIf="loading" class="spinner"></span>
<ng-content></ng-content>
</button>
`,
styles: [`
.btn {
padding: 12px 24px;
border: none;
border-radius: 4px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s ease;
display: inline-flex;
align-items: center;
gap: 8px;
&.btn-primary {
background-color: #007bff;
color: white;
&:hover:not(:disabled) {
background-color: #0056b3;
}
}
&.btn-secondary {
background-color: #6c757d;
color: white;
&:hover:not(:disabled) {
background-color: #545b62;
}
}
&.btn-danger {
background-color: #dc3545;
color: white;
&:hover:not(:disabled) {
background-color: #bb2d3b;
}
}
&:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.spinner {
display: inline-block;
width: 16px;
height: 16px;
border: 2px solid rgba(255, 255, 255, 0.3);
border-radius: 50%;
border-top: 2px solid white;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
}
`]
})
export class ButtonComponent {
@Input() variant: 'primary' | 'secondary' | 'danger' = 'primary';
@Input() disabled = false;
@Input() loading = false;
@Input() pulse = false;
@Input() ariaLabel: string = '';
}
Directives
typescript Copy code
// projects/my-lib/src/lib/directives/pulse.directive.ts
import { Directive, Input, OnInit, ElementRef, OnDestroy } from '@angular/core';
@Directive({
selector: '[libPulse]',
standalone: true
})
export class PulseDirective implements OnInit, OnDestroy {
@Input()
set libPulse(enabled: boolean) {
if (enabled) {
this.addPulseAnimation();
} else {
this.removePulseAnimation();
}
}
constructor(private el: ElementRef) {}
ngOnInit() {
this.injectStyles();
}
ngOnDestroy() {
this.removePulseAnimation();
}
private addPulseAnimation() {
this.el.nativeElement.classList.add('pulse-animation');
}
private removePulseAnimation() {
this.el.nativeElement.classList.remove('pulse-animation');
}
private injectStyles() {
if (document.getElementById('pulse-styles')) return;
const style = document.createElement('style');
style.id = 'pulse-styles';
style.textContent = `
@keyframes pulse {
0%, 100% {
box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.7);
}
50% {
box-shadow: 0 0 0 10px rgba(59, 130, 246, 0);
}
}
.pulse-animation {
animation: pulse 2s infinite;
}
`;
document.head.appendChild(style);
}
}
typescript Copy code
// projects/my-lib/src/lib/directives/disabled.directive.ts
import { Directive, Input, HostBinding } from '@angular/core';
@Directive({
selector: '[libDisabled]',
standalone: true
})
export class DisabledDirective {
@Input() libDisabled = false;
@HostBinding('disabled')
get isDisabled() {
return this.libDisabled;
}
@HostBinding('attr.aria-disabled')
get ariaDisabled() {
return this.libDisabled;
}
@HostBinding('class.lib-disabled')
get disabledClass() {
return this.libDisabled;
}
}
typescript Copy code
// projects/my-lib/src/lib/directives/index.ts
export * from './pulse.directive';
export * from './disabled.directive';
Card Component
typescript Copy code
// projects/my-lib/src/lib/card/card.component.ts
import { Component, Input } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BorderRadiusDirective } from '../directives/border-radius.directive';
@Component({
selector: 'lib-card',
standalone: true,
imports: [CommonModule, BorderRadiusDirective],
template: `
<div
class="card"
[libBorderRadius]="borderRadius"
[style.box-shadow]="shadow ? '0 4px 6px rgba(0, 0, 0, 0.1)' : 'none'"
>
<div *ngIf="title" class="card-header">
<h3>{{ title }}</h3>
</div>
<div class="card-body">
<ng-content></ng-content>
</div>
<div *ngIf="footer" class="card-footer">
{{ footer }}
</div>
</div>
`,
styles: [`
.card {
background: white;
border: 1px solid #e5e7eb;
transition: all 0.3s ease;
.card-header {
padding: 16px;
border-bottom: 1px solid #e5e7eb;
h3 {
margin: 0;
font-size: 18px;
font-weight: 600;
}
}
.card-body {
padding: 20px;
}
.card-footer {
padding: 16px;
background-color: #f9fafb;
border-top: 1px solid #e5e7eb;
font-size: 14px;
color: #6b7280;
}
}
`]
})
export class CardComponent {
@Input() title: string = '';
@Input() footer: string = '';
@Input() shadow = false;
@Input() borderRadius = 'md';
}
typescript Copy code
// projects/my-lib/src/lib/directives/border-radius.directive.ts
import { Directive, Input, HostBinding } from '@angular/core';
@Directive({
selector: '[libBorderRadius]',
standalone: true
})
export class BorderRadiusDirective {
@Input()
set libBorderRadius(size: 'sm' | 'md' | 'lg' | 'full') {
this.radiusSize = size;
}
private radiusSize: 'sm' | 'md' | 'lg' | 'full' = 'md';
@HostBinding('style.border-radius')
get borderRadius(): string {
const radiusMap = {
sm: '2px',
md: '4px',
lg: '8px',
full: '50%'
};
return radiusMap[this.radiusSize];
}
}
Badge Component
typescript Copy code
// projects/my-lib/src/lib/badge/badge.component.ts
import { Component, Input } from '@angular/core';
import { CommonModule } from '@angular/common';
import { PulseDirective } from '../directives/pulse.directive';
@Component({
selector: 'lib-badge',
standalone: true,
imports: [CommonModule, PulseDirective],
template: `
<span
class="badge"
[class]="'badge-' + variant"
[libPulse]="pulse"
>
<ng-content></ng-content>
</span>
`,
styles: [`
.badge {
display: inline-block;
padding: 4px 12px;
border-radius: 12px;
font-size: 12px;
font-weight: 600;
text-transform: uppercase;
&.badge-success {
background-color: #d1fae5;
color: #065f46;
}
&.badge-warning {
background-color: #fef3c7;
color: #92400e;
}
&.badge-danger {
background-color: #fee2e2;
color: #991b1b;
}
&.badge-info {
background-color: #dbeafe;
color: #0c2d6b;
}
}
`]
})
export class BadgeComponent {
@Input() variant: 'success' | 'warning' | 'danger' | 'info' = 'info';
@Input() pulse = false;
}
4. Storybook Configuration
typescript Copy code
// .storybook/main.ts
import type { StorybookConfig } from '@storybook/angular';
const config: StorybookConfig = {
stories: [
'../stories/**/*.stories.ts',
],
addons: [
'@storybook/addon-links',
'@storybook/addon-essentials',
'@storybook/addon-controls',
'@storybook/addon-actions',
'@storybook/addon-viewport',
'@storybook/addon-measure',
],
framework: {
name: '@storybook/angular',
options: {},
},
docs: {
autodocs: 'tag',
},
core: {
disableTelemetry: true,
},
webpackFinal: async (config) => {
return config;
},
};
export default config;
typescript Copy code
// .storybook/preview.ts
import type { Preview } from '@storybook/angular';
import { INITIAL_VIEWPORTS } from '@storybook/addon-viewport';
const preview: Preview = {
parameters: {
viewport: {
viewports: INITIAL_VIEWPORTS,
defaultViewport: 'iphone12',
},
actions: { argTypesRegex: '^on[A-Z].*' },
controls: {
expanded: true,
matchers: {
color: /(background|color)$/i,
date: /Date$/i,
},
},
layout: 'centered',
},
tags: ['autodocs'],
};
export default preview;
typescript Copy code
// .storybook/manager.ts
import { addons } from '@storybook/manager-api';
import { themes } from '@storybook/theming';
addons.setConfig({
theme: themes.light,
toolbar: {
title: {
hidden: false,
},
},
});
5. Stories with Directive Controls
typescript Copy code
// stories/button.stories.ts
import { Meta, StoryObj } from '@storybook/angular';
import { ButtonComponent } from '../projects/my-lib/src/lib/button/button.component';
import { action } from '@storybook/addon-actions';
const meta: Meta<ButtonComponent> = {
title: 'Components/Button',
component: ButtonComponent,
tags: ['autodocs'],
argTypes: {
variant: {
control: 'select',
options: ['primary', 'secondary', 'danger'],
table: {
category: 'Style',
},
},
disabled: {
control: 'boolean',
table: {
category: 'State',
},
description: 'Applies libDisabled directive',
},
loading: {
control: 'boolean',
table: {
category: 'State',
},
},
pulse: {
control: 'boolean',
table: {
category: 'Directives',
defaultValue: false,
},
description: 'Applies libPulse directive for animated effect',
},
},
parameters: {
viewport: {
defaultViewport: 'iphone12',
},
},
};
export default meta;
type Story = StoryObj<ButtonComponent>;
export const Primary: Story = {
args: {
variant: 'primary',
disabled: false,
loading: false,
pulse: false,
},
render: (args) => ({
props: args,
template: `<lib-button
[variant]="variant"
[disabled]="disabled"
[loading]="loading"
[pulse]="pulse"
>
Click Me
</lib-button>`,
}),
};
export const Secondary: Story = {
args: {
...Primary.args,
variant: 'secondary',
},
};
export const Danger: Story = {
args: {
...Primary.args,
variant: 'danger',
},
};
export const WithPulse: Story = {
args: {
...Primary.args,
pulse: true,
},
parameters: {
visualRegression: {
threshold: 0.001, // 0.1%
},
},
};
export const DisabledState: Story = {
args: {
...Primary.args,
disabled: true,
},
};
export const LoadingState: Story = {
args: {
...Primary.args,
loading: true,
},
};
export const AllVariants: Story = {
render: () => ({
template: `
<div style="display: flex; gap: 20px; align-items: center;">
<lib-button variant="primary">Primary</lib-button>
<lib-button variant="secondary">Secondary</lib-button>
<lib-button variant="danger">Danger</lib-button>
</div>
`,
}),
};
export const PulseAndDisabled: Story = {
args: {
pulse: true,
disabled: true,
},
parameters: {
visualRegression: {
threshold: 0.001,
},
},
};
typescript Copy code
// stories/card.stories.ts
import { Meta, StoryObj } from '@storybook/angular';
import { CardComponent } from '../projects/my-lib/src/lib/card/card.component';
const meta: Meta<CardComponent> = {
title: 'Components/Card',
component: CardComponent,
tags: ['autodocs'],
argTypes: {
title: {
control: 'text',
table: { category: 'Content' },
},
footer: {
control: 'text',
table: { category: 'Content' },
},
shadow: {
control: 'boolean',
table: { category: 'Style' },
description: 'Apply shadow effect',
},
borderRadius: {
control: 'select',
options: ['sm', 'md', 'lg', 'full'],
table: { category: 'Directives' },
description: 'Border radius via libBorderRadius directive',
},
},
};
export default meta;
type Story = StoryObj<CardComponent>;
export const Default: Story = {
args: {
title: 'Card Title',
footer: 'Card Footer',
shadow: false,
borderRadius: 'md',
},
render: (args) => ({
props: args,
template: `
<lib-card
[title]="title"
[footer]="footer"
[shadow]="shadow"
[borderRadius]="borderRadius"
>
<p>This is card content</p>
</lib-card>
`,
}),
};
export const WithShadow: Story = {
args: {
...Default.args,
shadow: true,
},
};
export const LargeBorderRadius: Story = {
args: {
...Default.args,
borderRadius: 'lg',
},
};
export const VariousRadii: Story = {
render: () => ({
template: `
<div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px;">
<lib-card title="Small" borderRadius="sm">Content</lib-card>
<lib-card title="Medium" borderRadius="md">Content</lib-card>
<lib-card title="Large" borderRadius="lg">Content</lib-card>
<lib-card title="Full" borderRadius="full">Content</lib-card>
</div>
`,
}),
};
typescript Copy code
// stories/badge.stories.ts
import { Meta, StoryObj } from '@storybook/angular';
import { BadgeComponent } from '../projects/my-lib/src/lib/badge/badge.component';
const meta: Meta<BadgeComponent> = {
title: 'Components/Badge',
component: BadgeComponent,
tags: ['autodocs'],
argTypes: {
variant: {
control: 'select',
options: ['success', 'warning', 'danger', 'info'],
table: { category: 'Style' },
},
pulse: {
control: 'boolean',
table: { category: 'Directives' },
description: 'Apply libPulse directive for animation',
},
},
};
export default meta;
type Story = StoryObj<BadgeComponent>;
export const Success: Story = {
args: {
variant: 'success',
pulse: false,
},
render: (args) => ({
props: args,
template: `<lib-badge [variant]="variant" [pulse]="pulse">Active</lib-badge>`,
}),
};
export const Warning: Story = {
args: { variant: 'warning', pulse: false },
render: (args) => ({
props: args,
template: `<lib-badge [variant]="variant" [pulse]="pulse">Warning</lib-badge>`,
}),
};
export const Danger: Story = {
args: { variant: 'danger', pulse: false },
render: (args) => ({
props: args,
template: `<lib-badge [variant]="variant" [pulse]="pulse">Error</lib-badge>`,
}),
};
export const WithPulse: Story = {
args: { variant: 'success', pulse: true },
render: (args) => ({
props: args,
template: `<lib-badge [variant]="variant" [pulse]="pulse">Live</lib-badge>`,
}),
parameters: {
visualRegression: {
threshold: 0.001,
},
},
};
export const AllVariants: Story = {
render: () => ({
template: `
<div style="display: flex; gap: 15px; align-items: center; flex-wrap: wrap;">
<lib-badge variant="success">Success</lib-badge>
<lib-badge variant="warning">Warning</lib-badge>
<lib-badge variant="danger">Danger</lib-badge>
<lib-badge variant="info">Info</lib-badge>
</div>
`,
}),
};
6. Visual Regression Testing Script
7. Baseline Update Script
8. GitHub Actions CI Configuration
yaml Copy code
# .github/workflows/visual-regression.yml
name: Visual Regression Tests
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main, develop ]
jobs:
visual-tests:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [18.x]
steps:
- uses: actions/checkout@v3
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build library
run: npm run build:lib
- name: Build Storybook
run: npm run build:storybook
- name: Upload Storybook
uses: actions/upload-artifact@v3
with:
name: storybook-build
path: storybook-static/
- name: Start static server
run: |
npx http-server storybook-static -p 6006 &
sleep 3
- name: Run visual regression tests
run: npm run test:visual:ci
- name: Upload test results
if: always()
uses: actions/upload-artifact@v3
with:
name: visual-regression-results
path: __visual_regression__/
- name: Comment PR with results
if: github.event_name == 'pull_request'
uses: actions/github-script@v6
with:
script: |
const fs = require('fs');
const results = JSON.parse(fs.readFileSync('__visual_regression__/results.json', 'utf8'));
const comment = `## 🎨 Visual Regression Test Results
- **Total Tests**: ${results.totalTests}
- **✅ Passed**: ${results.passedTests}
- **❌ Failed**: ${results.failedTests}
- **Threshold**: 0.1%
${results.failedTests > 0 ? '### Failed Tests\n' + results.results
.filter(r => !r.passed)
.map(r => `- ${r.name}: ${r.percentDifference.toFixed(4)}%`)
.join('\n') : '✅ All tests passed!'}
`;
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: comment
});
- name: Fail if regressions detected
if: failure()
run: exit 1
9. TypeScript Configuration
json Copy code
{
"compilerOptions": {
"target": "ES2020",
"module": "ES2020",
"lib": ["ES2020", "DOM"],
"declaration": true,
"outDir": "./dist",
"rootDir": "./",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"resolveJsonModule": true
},
"include": [
"projects/**/*.ts",
"stories/**/*.ts",
"scripts/**/*.ts"
],
"exclude": ["node_modules", "dist"]
}
10. Usage Guide
Development
bash Copy code
# Install dependencies
npm install
# Build library
npm run build:lib
# Start Storybook
npm run storybook
# Navigate to http://localhost:6006
# Create visual baselines
npm run test:visual:update
# Run local visual regression tests
npm run test:visual
Visual Regression Testing Features
typescript Copy code
// Stories automatically get tested via their story ID
// Directive controls are fully interactive in Storybook:
// 1. Pulse Directive Toggle
<lib-button [pulse]="true">Pulsing Button</lib-button>
// 2. Disabled Directive Toggle
<lib-button [disabled]="true">Disabled</lib-button>
// 3. Border Radius Directive Toggle
<lib-card [borderRadius]="'lg'">large radius</lib-card>
// Visual regression captures all directive states
CI Pipeline
Tests run on push/PR to main/develop
Compares against baselines with 0.1% threshold
Generates diff images on failure
Comments on PRs with results
Fails CI if threshold exceeded
How Controls Work
The Storybook controls (knobs) directly toggle the Angular directives:
typescript Copy code
// In story file:
export const WithPulse: Story = {
args: {
pulse: true, // ← This gets bound to [libPulse]=""
},
};
// When user toggles checkbox in Storybook UI:
// 1. Knob value changes
// 2. Template binding updates
// 3. Directive @Input changes
// 4. Directive applies/removes animation
// 5. Visual regression captures new state
This setup provides production-grade component library testing with visual regression, directive control, and CI integration! 🚀