Providing complete Angular library setup with Storybook, Chromatic, and local visual testing
This delivers Angular component and directive code with Storybook stories using knobs to toggle the directive, plus Chromatic config enforcing a 0.1% visual diff threshold, and a local Puppeteer + pixelmatch script to fail CI if visual regressions exceed 0.1%. It includes scripts and GitHub Action snippets for both testing methods.
Below is a minimal end‑to‑end setup for an Angular component library with Storybook, visual regression testing (either Chromatic or a local Puppeteer + pixelmatch script), and a checkbox “knob” that toggles an Angular directive on/off.
1) Install Storybook for Angular
bash Copy code
# In an Angular workspace
npx sb@latest init --type angular
# Add knobs (or use Controls from addon-essentials)
npm i -D @storybook/addon-knobs
# (Optional) Add Chromatic
npm i -D chromatic
.storybook/main.js
js Copy code
module.exports = {
stories: ['../src/stories/**/*.stories.ts'],
addons: [
'@storybook/addon-essentials',
'@storybook/addon-knobs', // for the checkbox knob
],
};
.storybook/preview.ts
ts Copy code
import { withKnobs } from '@storybook/addon-knobs';
import { addDecorator } from '@storybook/angular';
addDecorator(withKnobs);
// Chromatic global threshold = 0.1% (0.001)
export const parameters = {
chromatic: { diffThreshold: 0.001 },
};
2) Example component + directive in your library
src/lib/highlight.directive.ts
ts Copy code
import { Directive, HostBinding, Input } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@Input() appHighlight = false;
@HostBinding('class.highlighted') get highlighted(): boolean {
return this.appHighlight;
}
}
src/lib/button/button.component.ts
ts Copy code
import { Component, Input } from '@angular/core';
@Component({
selector: 'ui-button',
template: `
<button [appHighlight]="highlight">{{ label }}</button>
`,
styles: [`
button {
padding: 10px 16px;
border-radius: 4px;
border: 1px solid #ccc;
background: white;
cursor: pointer;
}
.highlighted {
box-shadow: 0 0 0 2px #2196f3;
}
`]
})
export class ButtonComponent {
@Input() label = 'Click me';
@Input() highlight = false;
}
3) Story with a checkbox “knob” toggling the directive
src/stories/button.stories.ts
ts Copy code
import { Meta, Story, moduleMetadata } from '@storybook/angular';
import { boolean, text } from '@storybook/addon-knobs';
import { ButtonComponent } from '../lib/button/button.component';
import { HighlightDirective } from '../lib/highlight.directive';
export default {
title: 'Components/Button',
decorators: [
moduleMetadata({
declarations: [ButtonComponent, HighlightDirective],
}),
],
parameters: {
chromatic: { diffThreshold: 0.001 }, // 0.1%
},
} as Meta;
export const Default: Story = () => {
const highlight = boolean('Highlight (directive on/off)', false);
const label = text('Label', 'Click me');
return {
component: ButtonComponent,
props: {
label,
highlight,
},
};
};
When you check the “Highlight (directive on/off)” box in Storybook, the appHighlight directive toggles, adding/removing the .highlighted class.
4) Chromatic option (hosted VRT)
Add a script with your Chromatic project token:
json Copy code
// package.json
{
"scripts": {
"chromatic": "chromatic --project-token=<YOUR_TOKEN>"
}
}
In CI (GitHub Actions example):
yaml Copy code
# .github/workflows/chromatic.yml
name: Chromatic
on: [push, pull_request]
jobs:
chromatic:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v3
with:
node-version: '18'
- run: npm ci
- run: npm run chromatic -- --exit-zero-on-changes
Chromatic compares snapshots on every build. With diffThreshold: 0.001 in parameters, builds will fail if the pixel diff exceeds 0.1%.
5) Local Puppeteer + pixelmatch option
Install dev dependencies:
bash Copy code
npm i -D puppeteer pixelmatch pngjs http-server
Add an npm script to build and serve Storybook, then run VRT:
json Copy code
// package.json
{
"scripts": {
"build-storybook": "build-storybook -c .storybook -o storybook-static",
"serve-storybook": "http-server storybook-static -p 6006",
"vrt": "npm run build-storybook && npm run serve-storybook & node scripts/vrt.js"
}
}
scripts/vrt.js
js Copy code
const fs = require('fs');
const path = require('path');
const pixelmatch = require('pixelmatch');
const { PNG } = require('pngjs');
const puppeteer = require('puppeteer');
const STORY_URL = 'http://localhost:6006/iframe.html?id=components-button--default';
const BASELINE_PATH = path.join(__dirname, 'vrt-baseline', 'button-default.png');
const CURRENT_PATH = path.join(__dirname, 'vrt-output', 'button-default.png');
const THRESHOLD_PERCENT = 0.1; // 0.1%
(async () => {
const browser = await puppeteer.launch({ headless: 'new' });
const page = await browser.newPage();
await page.setViewport({ width: 400, height: 200 });
await page.goto(STORY_URL, { waitUntil: 'networkidle2' });
await fs.promises.mkdir(path.dirname(CURRENT_PATH), { recursive: true });
await page.screenshot({ path: CURRENT_PATH });
await browser.close();
if (!fs.existsSync(BASELINE_PATH)) {
console.warn('Baseline does not exist. Saving current as baseline.');
await fs.promises.mkdir(path.dirname(BASELINE_PATH), { recursive: true });
fs.copyFileSync(CURRENT_PATH, BASELINE_PATH);
process.exit(0);
}
const baseline = PNG.sync.read(fs.readFileSync(BASELINE_PATH));
const current = PNG.sync.read(fs.readFileSync(CURRENT_PATH));
const { width, height } = baseline;
const diff = new PNG({ width, height });
const diffPixels = pixelmatch(
baseline.data,
current.data,
diff.data,
width,
height,
{ threshold: 0.1 } // pixel sensitivity
);
const totalPixels = width * height;
const diffPercent = (diffPixels / totalPixels) * 100;
if (diffPercent > THRESHOLD_PERCENT) {
fs.writeFileSync(path.join(__dirname, 'vrt-output', 'button-default-diff.png'), PNG.sync.write(diff));
console.error(`❌ Visual diff too high: ${diffPercent.toFixed(3)}% > ${THRESHOLD_PERCENT}%`);
process.exit(1);
} else {
console.log(`✅ Visual diff OK: ${diffPercent.toFixed(3)}% <= ${THRESHOLD_PERCENT}%`);
process.exit(0);
}
})();
Run locally or in CI:
This will fail with exit code 1 if pixel difference exceeds 0.1% .
Summary
Storybook + knobs toggles an Angular directive on your component.
For visual regression you can use Chromatic (hosted) or a local Puppeteer + pixelmatch script.
CI fails when pixel differences exceed 0.1% via diffThreshold (Chromatic) or custom threshold check (local script).