@public-ui/visual-tests 4.0.0-alpha.0 → 4.0.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # KoliBri - Visual Tests
2
2
 
3
+ Utilities for screenshot based regression testing of KoliBri themes.
4
+
5
+ [![npm](https://img.shields.io/npm/v/@public-ui/visual-tests)](https://www.npmjs.com/package/@public-ui/components)
6
+ [![license](https://img.shields.io/npm/l/@public-ui/visual-tests)](https://github.com/public-ui/kolibri/blob/main/LICENSE)
7
+ [![downloads](https://img.shields.io/npm/dt/@public-ui/visual-tests)](https://www.npmjs.com/package/@public-ui/visual-tests)
8
+ [![issues](https://img.shields.io/github/issues/public-ui/kolibri)](https://github.com/public-ui/kolibri/issues)
9
+ [![pull requests](https://img.shields.io/github/issues-pr/public-ui/kolibri)](https://github.com/public-ui/kolibri/pulls)
10
+ [![size](https://img.shields.io/bundlephobia/min/@public-ui/visual-tests)](https://bundlephobia.com/result?p=@public-ui/visual-tests)
11
+ ![contributors](https://img.shields.io/github/contributors/public-ui/kolibri)
12
+
3
13
  ## Motivation
4
14
 
5
15
  The `KoliBri` Visual Tests provide a way to add visual regression testing to **theme** modules.
@@ -7,11 +17,23 @@ It takes screenshots of every component defined in the [React Sample App](https:
7
17
 
8
18
  ## Installation
9
19
 
20
+ It is recommended to configure NPM via `.npmrc`:
21
+
22
+ ```bash
23
+ # - npm
24
+ engine-strict=true
25
+ save-exact=true
26
+
27
+ # - pnpm
28
+ shamefully-hoist=true # this is required for the visual tests to work
29
+ workspace-concurrency=1
30
+ ```
31
+
10
32
  You can install the `KoliBri` Visual Tests with `npm`, `pnpm` or `yarn`:
11
33
 
12
34
  ```bash
13
35
  npm i -D @public-ui/visual-tests
14
- pnpm i -D @public-ui/visual-tests
36
+ pnpm i -D @public-ui/visual-tests # recommended
15
37
  yarn add -D @public-ui/visual-tests
16
38
  ```
17
39
 
@@ -21,17 +43,24 @@ Add the following npm scripts to the theme's `package.json`:
21
43
 
22
44
  ```json
23
45
  {
24
- "scripts": {
25
- "test": "THEME_MODULE=src/index THEME_EXPORT=THEME_NAME kolibri-visual-test",
26
- "test-update": "THEME_MODULE=src/index THEME_EXPORT=THEME_NAME kolibri-visual-test --update-snapshots",
27
- }
46
+ "scripts": {
47
+ "test": "THEME_MODULE=src/index THEME_EXPORT=THEME_NAME kolibri-visual-test",
48
+ "test:update:e2e": "THEME_MODULE=src/index THEME_EXPORT=THEME_NAME kolibri-visual-test --update-snapshots=changed"
49
+ }
28
50
  }
29
51
  ```
30
52
 
31
- * `THEME_MODULE` defines the relative path to the TypeScript module containing the the theme definitions. Without file extension.
32
- * `THEME_EXPERT` defines the name of the export within the the module. (e.g., `export const THEME_NAME = {/**/};`) Defaults to `default`.
53
+ ### Environment variables
54
+
55
+ - `THEME_MODULE`: Define the relative path to the TypeScript module containing the theme definitions. Without file extension.
56
+ - `THEME_EXPERT`: Define the name of the export within the module. (e.g., `export const THEME_NAME = {/**/};`) Defaults to `default`.
57
+ - `KOLIBRI_VISUAL_TESTS_TIMEOUT`: Define the Playwright [test timeout](https://playwright.dev/docs/test-timeouts).
58
+ - `KOLIBRI_VISUAL_TESTS_EXPECT_TIMEOUT`: Define the Playwright [expect timeout](https://playwright.dev/docs/test-timeouts).
59
+ - `KOLIBRI_VISUAL_TESTS_COLOR_SCHEME`: Choose the [CSS color scheme](https://developer.mozilla.org/docs/Web/CSS/@media/prefers-color-scheme) for the browser context. Supported values are `light` (default) and `dark`.
33
60
 
34
61
  Run the tests with `npm test`. The first time, this will create a new folder `snapshots` which is supposed to be committed to the repository.
35
62
  In the following runs, new screenshots will be compared to this reference.
36
63
 
37
- To update the reference screenshots call `npm run test-update`.
64
+ To update the reference screenshots call `npm run test:update`.
65
+
66
+ For details on theming see the [default theme README](../../themes/default/README.md).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@public-ui/visual-tests",
3
- "version": "4.0.0-alpha.0",
3
+ "version": "4.0.0-alpha.10",
4
4
  "license": "EUPL-1.2",
5
5
  "homepage": "https://public-ui.github.io",
6
6
  "repository": {
@@ -15,6 +15,9 @@
15
15
  "name": "Informationstechnikzentrum Bund",
16
16
  "email": "kolibri@itzbund.de"
17
17
  },
18
+ "engines": {
19
+ "pnpm": "^10"
20
+ },
18
21
  "type": "module",
19
22
  "sideEffects": false,
20
23
  "description": "Provides utility to run visual regression tests for themes.",
@@ -22,19 +25,24 @@
22
25
  "kolibri-visual-test": "src/index.js"
23
26
  },
24
27
  "dependencies": {
25
- "@playwright/test": "1.49.0",
26
- "axe-playwright": "2.0.3",
27
- "portfinder": "1.0.32",
28
- "serve": "14.2.4",
29
- "@public-ui/sample-react": "4.0.0-alpha.0"
28
+ "@axe-core/playwright": "4.11.0",
29
+ "axe-html-reporter": "2.2.11",
30
+ "portfinder": "1.0.38",
31
+ "serve": "14.2.5",
32
+ "@public-ui/sample-react": "4.0.0-alpha.10"
30
33
  },
31
34
  "devDependencies": {
32
- "@babel/eslint-parser": "7.25.9",
33
- "@babel/plugin-syntax-import-attributes": "7.26.0",
34
- "@babel/preset-env": "7.26.0",
35
+ "@babel/eslint-parser": "7.28.5",
36
+ "@babel/plugin-syntax-import-attributes": "7.27.1",
37
+ "@babel/preset-env": "7.28.5",
38
+ "@playwright/test": "1.57.0",
35
39
  "eslint": "8.57.1",
36
- "knip": "5.37.1",
37
- "prettier": "3.3.3"
40
+ "knip": "5.73.4",
41
+ "prettier": "3.7.4",
42
+ "prettier-plugin-organize-imports": "4.3.0"
43
+ },
44
+ "peerDependencies": {
45
+ "@playwright/test": "1.57.0"
38
46
  },
39
47
  "files": [
40
48
  "playwright.config.js",
@@ -43,8 +51,8 @@
43
51
  ],
44
52
  "scripts": {
45
53
  "format": "prettier --check src",
46
- "lint": "eslint src",
47
- "unused": "knip",
48
- "postinstall": "pnpm exec playwright install"
54
+ "lint": "pnpm lint:eslint",
55
+ "lint:eslint": "eslint src",
56
+ "unused": "knip"
49
57
  }
50
58
  }
@@ -2,19 +2,34 @@ import { defineConfig, devices } from '@playwright/test';
2
2
  import * as path from 'path';
3
3
  import * as process from 'process';
4
4
 
5
- const PORT = Number(process.env.KOLIBRI_VISUAL_TEST_PORT);
6
- const URL = `http://localhost:${PORT}`;
5
+ // Validate and set ENVs
6
+ const PORT = parseInt(process.env.KOLIBRI_VISUAL_TEST_PORT || '', 10);
7
+ const BASE_URL = `http://localhost:${PORT}`;
7
8
 
8
- console.log('Serving React Sample app:', URL);
9
+ const CWD = process.env.KOLIBRI_CWD ?? '';
10
+ const TIMEOUT = parseInt(process.env.KOLIBRI_VISUAL_TESTS_TIMEOUT || '15000', 10);
11
+ const EXPECT_TIMEOUT = parseInt(process.env.KOLIBRI_VISUAL_TESTS_EXPECT_TIMEOUT || '5000', 10);
12
+ const BUILD_PATH = process.env.KOLIBRI_VISUAL_TESTS_BUILD_PATH ?? '';
13
+ const THEME = (process.env.THEME_EXPORT || 'default').toLocaleLowerCase();
14
+
15
+ const VALID_COLOR_SCHEMES = ['light', 'dark'];
16
+ const colorSchemeInput = process.env.KOLIBRI_VISUAL_TESTS_COLOR_SCHEME;
17
+ const colorSchema = (colorSchemeInput || 'light').toLocaleLowerCase();
18
+
19
+ if (!VALID_COLOR_SCHEMES.includes(colorSchema)) {
20
+ throw new Error(
21
+ `Environment variable KOLIBRI_VISUAL_TESTS_COLOR_SCHEME must be one of "${VALID_COLOR_SCHEMES.join('", "')}" (received "${colorSchemeInput}").`,
22
+ );
23
+ }
9
24
 
10
25
  /**
11
26
  * See https://playwright.dev/docs/test-configuration.
12
27
  */
13
28
  export default defineConfig({
14
29
  testDir: './tests',
15
- snapshotDir: path.join(process.env.KOLIBRI_CWD ?? '', 'snapshots'),
30
+ snapshotDir: path.join(CWD, 'snapshots'),
16
31
  // snapshotPathTemplate: '',
17
- outputDir: path.join(process.env.KOLIBRI_CWD ?? '', 'test-results'),
32
+ outputDir: path.join(CWD, 'test-results'),
18
33
  /* Run tests in files in parallel */
19
34
  fullyParallel: true,
20
35
  /* Fail the build on CI if you accidentally left test.only in the source code. */
@@ -24,18 +39,22 @@ export default defineConfig({
24
39
  /* Opt out of parallel tests on CI. */
25
40
  workers: process.env.CI ? 1 : undefined,
26
41
  /* Allow to override the expectation timeout for slow environments */
27
- timeout: process.env.KOLIBRI_VISUAL_TESTS_TIMEOUT ? Number(process.env.KOLIBRI_VISUAL_TESTS_TIMEOUT) : undefined,
42
+ timeout: TIMEOUT,
28
43
  /* Reporter to use. See https://playwright.dev/docs/test-reporters */
29
44
  reporter: 'line',
30
45
  /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
31
46
  use: {
32
47
  /* Base URL to use in actions like `await page.goto('/')`. */
33
- baseURL: URL,
48
+ baseURL: BASE_URL,
34
49
 
35
50
  /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
36
51
  trace: 'on-first-retry',
37
52
  },
38
53
 
54
+ expect: {
55
+ timeout: EXPECT_TIMEOUT,
56
+ },
57
+
39
58
  /* Configure projects for major browsers */
40
59
  projects: [
41
60
  // {
@@ -55,8 +74,9 @@ export default defineConfig({
55
74
  /* Run your local dev server before starting the tests */
56
75
  webServer: {
57
76
  command: `npx serve -p ${PORT}`,
58
- cwd: path.resolve(process.env.KOLIBRI_VISUAL_TESTS_BUILD_PATH),
59
- url: URL,
77
+ cwd: path.resolve(BUILD_PATH),
78
+ url: BASE_URL,
60
79
  reuseExistingServer: false,
61
80
  },
81
+ snapshotPathTemplate: `{snapshotDir}/theme-${THEME}${colorSchema === 'light' ? '' : `-${colorSchema}`}/{arg}-{projectName}-{platform}{ext}`,
62
82
  });
package/src/index.js CHANGED
@@ -1,12 +1,14 @@
1
- import child_process from 'node:child_process';
2
- import path from 'node:path';
3
- import { fileURLToPath, pathToFileURL } from 'url';
4
1
  import * as crypto from 'crypto';
5
2
  import * as fs from 'fs';
3
+ import { readFile } from 'fs/promises';
4
+ import child_process from 'node:child_process';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
6
7
  import portfinder from 'portfinder';
7
8
  import * as process from 'process';
9
+ import { fileURLToPath, pathToFileURL } from 'url';
8
10
 
9
- const tempDir = process.env.RUNNER_TEMP || process.env.TMPDIR; // TODO: Check on Windows
11
+ const tempDir = process.env.RUNNER_TEMP || process.env.TMPDIR || os.tmpdir(); // TODO: Check on Windows
10
12
 
11
13
  if (!process.env.THEME_MODULE) {
12
14
  throw new Error('Environment variable THEME_MODULE not specified.');
@@ -18,15 +20,8 @@ if (!tempDir) {
18
20
  process.env.THEME_MODULE = path.join(process.cwd(), process.env.THEME_MODULE); // Use current working directory (i.e. the theme folder) to complete module path
19
21
  const visualsTestModulePath = fileURLToPath(new URL('..', import.meta.url));
20
22
  const binaryPath = fileURLToPath(new URL('../node_modules/.bin', import.meta.url));
21
-
22
- let sampleReactPath = '../node_modules/@public-ui/sample-react';
23
- let backSteps = ``;
24
- let workingDir = null;
25
- do {
26
- const url = new URL(backSteps + sampleReactPath, import.meta.url);
27
- workingDir = fileURLToPath(url);
28
- backSteps += `../`;
29
- } while (!fs.existsSync(workingDir) && path.resolve(process.cwd(), backSteps) !== '/');
23
+ const sampleReactPackageJsonPath = import.meta.resolve('@public-ui/sample-react/package.json');
24
+ const workingDir = fileURLToPath(path.dirname(sampleReactPackageJsonPath));
30
25
 
31
26
  if (!fs.existsSync(workingDir)) {
32
27
  throw new Error('Could not find React Sample App package. Please install it with "npm install @public-ui/sample-react".');
@@ -35,19 +30,25 @@ if (!fs.existsSync(workingDir)) {
35
30
  const buildPath = path.join(tempDir, `kolibri-visual-testing-build-${crypto.randomUUID()}`);
36
31
  const rawPackageJsonPath = new URL(path.join(workingDir, 'package.json'), import.meta.url).href;
37
32
  const packageJsonPath = process.platform === 'win32' ? pathToFileURL(rawPackageJsonPath) : rawPackageJsonPath;
38
- const packageJson = await import(packageJsonPath, {
39
- assert: { type: 'json' },
40
- });
33
+ const packageJsonContent = await readFile(new URL(packageJsonPath, import.meta.url), 'utf8');
34
+ const packageJson = JSON.parse(packageJsonContent);
41
35
 
42
36
  console.log(`
43
- Building React Sample App (v${packageJson?.default?.version ?? '#.#.#'}) …`);
37
+ Building React Sample App (v${packageJson?.version ?? '#.#.#'}) …`);
44
38
 
45
- child_process.spawnSync('pnpm', ['run', 'build', '--', `--output-path="${buildPath}"`], {
39
+ const buildResult = child_process.spawnSync('pnpm', ['run', 'build', `--outDir="${buildPath}"`], {
46
40
  cwd: workingDir,
47
41
  encoding: 'utf-8',
48
42
  shell: true,
49
43
  });
50
44
 
45
+ if (buildResult.status !== 0) {
46
+ console.log('Build status:', buildResult.status);
47
+ console.log('Build stdout:', buildResult.stdout);
48
+ console.log('Build stderr:', buildResult.stderr);
49
+ console.log('Build error:', buildResult.error);
50
+ }
51
+
51
52
  console.log(`React Sample App build finished. Directory:`, buildPath);
52
53
 
53
54
  void (async () => {
@@ -1,7 +1,13 @@
1
+ import AxeBuilder from '@axe-core/playwright';
1
2
  import { test } from '@playwright/test';
2
- import { checkA11y, injectAxe } from 'axe-playwright';
3
+ import axeHtmlReporter from 'axe-html-reporter';
4
+ import process from 'process';
3
5
  import { ROUTES } from './sample-app.routes.js';
4
6
 
7
+ const { createHtmlReport } = axeHtmlReporter;
8
+
9
+ const AXE_TAGS = ['best-practices', 'wcag2a', 'wcag2aa', 'wcag21aa'];
10
+
5
11
  const themeName = (process.env.THEME_EXPORT || 'default').toLocaleLowerCase();
6
12
  const rename = (snapshotName) => {
7
13
  const result = snapshotName
@@ -24,6 +30,25 @@ const rename = (snapshotName) => {
24
30
  return result;
25
31
  };
26
32
 
33
+ const sanitizeRouteForReport = (route) => route.replace(/[/?]/g, '-').replace(/^-+/, '') || 'root';
34
+
35
+ const buildReportOptions = (testInfo, route) => ({
36
+ projectKey: `axe-${themeName}`,
37
+ reportFileName: `${sanitizeRouteForReport(route)}.html`,
38
+ outputDirPath: rename(testInfo.outputDir),
39
+ outputDir: `axe-${themeName}`,
40
+ });
41
+
42
+ const logViolations = (route, violations) => {
43
+ if (!violations?.length) {
44
+ return;
45
+ }
46
+ console.warn(`Axe found ${violations.length} violation(s) on ${route}`);
47
+ for (const violation of violations) {
48
+ console.warn(`- ${violation.id}: ${violation.help} (${violation.nodes.length} nodes)`);
49
+ }
50
+ };
51
+
27
52
  // https://playwright.dev/docs/emulation
28
53
  test.use({
29
54
  colorScheme: 'light',
@@ -36,44 +61,40 @@ test.use({
36
61
  },
37
62
  });
38
63
 
39
- const blocklist = [];
40
-
41
64
  ROUTES.forEach((options, route) => {
42
- if (blocklist.includes(route)) {
65
+ // Skip unnecessary axe tests
66
+ if (options?.axe?.skip === true || process.argv.includes('--update-snapshots')) {
43
67
  return;
44
68
  }
45
69
  test(`snapshot for ${route}`, async ({ page }, testInfo) => {
46
- const outputPath = rename(testInfo.outputDir);
47
- await page.goto(`/#${route}?hideMenus`, { waitUntil: 'networkidle' });
48
- if (options?.viewportSize) {
49
- await page.setViewportSize(options.viewportSize);
70
+ const hideMenusParam = `${route.includes('?') ? '&' : '?'}hideMenus`;
71
+ await page.goto(`/#${route}${hideMenusParam}`);
72
+ await page.waitForLoadState('networkidle');
73
+ await page.addStyleTag({
74
+ content: `
75
+ * {
76
+ transition: none !important;
77
+ animation: none !important;
78
+ }
79
+ `,
80
+ });
81
+ if (options?.snapshot?.viewportSize) {
82
+ await page.setViewportSize(options?.snapshot?.viewportSize);
50
83
  }
51
- if (options?.waitForTimeout) {
52
- await page.waitForTimeout(options.waitForTimeout);
84
+ if (options?.snapshot?.waitForTimeout) {
85
+ await page.waitForTimeout(options?.snapshot?.waitForTimeout);
53
86
  }
54
- await injectAxe(page);
55
- await checkA11y(
56
- page,
57
- undefined,
58
- {
59
- axeOptions: {
60
- runOnly: {
61
- type: 'tag',
62
- values: ['best-practices', 'wcag2a', 'wcag2aa', 'wcag21aa'],
63
- },
64
- },
65
- detailedReport: true,
66
- detailedReportOptions: {
67
- html: true,
68
- },
69
- },
70
- options?.axe?.skipFailures ?? true,
71
- 'html',
72
- {
73
- outputDirPath: outputPath.replace(/\/[^/]+$/, ''),
74
- outputDir: `axe-${themeName}`,
75
- reportFileName: `${route.replace('/', '-')}.html`,
76
- },
77
- );
87
+
88
+ const builder = new AxeBuilder({ page }).withTags(AXE_TAGS);
89
+ const results = await builder.analyze();
90
+ await testInfo.attach('axe-results', {
91
+ body: JSON.stringify(results, null, 2),
92
+ contentType: 'application/json',
93
+ });
94
+ createHtmlReport({
95
+ results,
96
+ options: buildReportOptions(testInfo, route),
97
+ });
98
+ logViolations(route, results.violations);
78
99
  });
79
100
  });