Skip to content

Instantly share code, notes, and snippets.

@fgeierst
Last active December 8, 2025 09:13
Show Gist options
  • Select an option

  • Save fgeierst/b7e52c894ea8eadc03207ec5803e3e03 to your computer and use it in GitHub Desktop.

Select an option

Save fgeierst/b7e52c894ea8eadc03207ec5803e3e03 to your computer and use it in GitHub Desktop.
Design tokens snapshot test vitest
import { describe, it, expect, beforeAll } from 'vitest';
import fs from 'node:fs';
import path from 'node:path';
import { globSync } from 'glob'; // requires: npm i -D glob
const BUILD_DIR = path.resolve(__dirname, 'build');
const SNAPSHOT_DIR = path.resolve(__dirname, '__snapshots__');
describe('All Build Outputs', () => {
// 1. Find ALL files in build dir (ignoring folders)
// cwd sets the 'current working directory' for the search
const allFiles = globSync('**/*.*', { cwd: BUILD_DIR });
// 2. Generate a test for every single file found
it.each(allFiles)('snapshot match: %s', (fileName) => {
const content = fs.readFileSync(path.join(BUILD_DIR, fileName), 'utf-8');
expect(content).toMatchFileSnapshot(path.join(SNAPSHOT_DIR, fileName));
});
});
import { describe, it, expect, beforeAll } from 'vitest';
import fs from 'node:fs';
import path from 'node:path';
import { execSync } from 'node:child_process';
const BUILD_DIR = path.resolve(__dirname, 'build');
const SNAPSHOT_DIR = path.resolve(__dirname, '__snapshots__');
// Helper to remove timestamps based on file extension/content
const sanitizeContent = (content: string) => {
return content
// Regex explanation:
// "Generated on" -> matches the literal text Style Dictionary uses
// ".*" -> matches the rest of the line (the changing date)
// "g" -> global flag (just in case)
.replace(/Generated on.*/g, 'Generated on [TIMESTAMP]');
};
describe('Token Output', () => {
beforeAll(() => {
execSync('npm run build', { stdio: 'inherit' });
});
const outputFiles = [
'css/variables.css',
'ios/StyleDictionary.swift',
'android/colors.xml',
];
it.each(outputFiles)('matches snapshot for %s', (fileName) => {
const filePath = path.join(BUILD_DIR, fileName);
const rawContent = fs.readFileSync(filePath, 'utf-8');
// CLEAN THE CONTENT BEFORE SNAPSHOTTING
const cleanContent = sanitizeContent(rawContent);
expect(cleanContent).toMatchFileSnapshot(
path.join(SNAPSHOT_DIR, fileName)
);
});
});
const StyleDictionary = require('style-dictionary');
// 1. Register a custom file header
StyleDictionary.registerFileHeader({
name: 'myCustomHeader',
fileHeader: (defaultMessage) => {
return [
'Do not edit directly',
'Built by My Design System'
];
}
});
// 2. Use it in your config
module.exports = {
source: ['tokens/**/*.json'],
platforms: {
css: {
files: [{
destination: 'variables.css',
format: 'css/variables',
options: {
fileHeader: 'myCustomHeader' // Use the static header
}
}]
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment