@chromatic-com/vitest 0.0.8 → 0.0.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/dist/index.d.ts CHANGED
@@ -45,7 +45,10 @@ interface ChromaticConfig {
45
45
  * Options that can be set per test, suite or module via `configure()`
46
46
  * - `assetDomains` is excluded as it can only be configured globally on the plugin
47
47
  */
48
- type ConfigureOptions = Omit<ChromaticConfig, 'assetDomains'>;
48
+ type ConfigureOptions = {
49
+ /** Custom title to be shown in Chromatic. Default is derived from test file name. */
50
+ title?: string;
51
+ } & Omit<ChromaticConfig, 'assetDomains'>;
49
52
 
50
53
  /**
51
54
  * Configure options for the current scope.
package/dist/plugin.d.ts CHANGED
@@ -64,6 +64,25 @@ interface Options extends ChromaticConfig {
64
64
  * @default 100
65
65
  */
66
66
  idleNetworkInterval?: number;
67
+ /**
68
+ * Logger used to report status of captured archives.
69
+ *
70
+ * @default true
71
+ */
72
+ reporter?: boolean | {
73
+ /**
74
+ * Whether the reporter is enabled.
75
+ *
76
+ * @default true
77
+ */
78
+ enabled?: boolean;
79
+ /**
80
+ * Log information about captured archives during test run.
81
+ *
82
+ * @default true
83
+ */
84
+ verbose?: boolean;
85
+ };
67
86
  }
68
87
 
69
88
  /**
package/dist/plugin.js CHANGED
@@ -3369,8 +3369,8 @@ var require_srcset = __commonJS({
3369
3369
 
3370
3370
  // src/node/plugin.ts
3371
3371
  import { rmSync } from "node:fs";
3372
- import { resolve as resolve2 } from "node:path";
3373
- import colors from "tinyrainbow";
3372
+ import { resolve as resolve3 } from "node:path";
3373
+ import colors2 from "tinyrainbow";
3374
3374
 
3375
3375
  // ../shared/src/utils/logger.ts
3376
3376
  var logger = process.env.LOG ? console : {
@@ -3871,6 +3871,7 @@ __name(viewportToString, "viewportToString");
3871
3871
  var sanitize = /* @__PURE__ */ __name((string) => {
3872
3872
  return string.toLowerCase().replace(/[ ’–—―′¿'`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, "-").replace(/[\r\n]/g, "-").replace(/-+/g, "-").replace(/^-+/, "").replace(/-+$/, "");
3873
3873
  }, "sanitize");
3874
+ var collapseNewlines = /* @__PURE__ */ __name((title) => title.replace(/[\r\n]+/g, " ").trim(), "collapseNewlines");
3874
3875
 
3875
3876
  // ../shared/src/write-archive/snapshot-files.ts
3876
3877
  var SNAPSHOT_FILE_EXT = "snapshot.json";
@@ -3891,47 +3892,58 @@ function snapshotFileName(snapshotId2, viewport) {
3891
3892
  __name(snapshotFileName, "snapshotFileName");
3892
3893
 
3893
3894
  // ../shared/src/write-archive/stories-files.ts
3895
+ import { storyNameFromExport, toId } from "storybook/internal/csf";
3894
3896
  var STORIES_FILE_EXT = "stories.json";
3897
+ var uniqueId = {
3898
+ value: 1
3899
+ };
3895
3900
  function storiesFileName(testTitle) {
3896
3901
  const fileName = [
3897
- sanitize(testTitle),
3902
+ sanitize(testTitle) + "-" + uniqueId.value++,
3898
3903
  STORIES_FILE_EXT
3899
3904
  ].join(".");
3900
3905
  const maxByteLength = MAX_FILE_NAME_BYTE_LENGTH - 25;
3901
3906
  return truncateFileName(fileName, maxByteLength);
3902
3907
  }
3903
3908
  __name(storiesFileName, "storiesFileName");
3904
- function createStories(title, domSnapshots, chromaticStorybookParams) {
3909
+ function createStories(storyTitle, domSnapshots, chromaticStorybookParams) {
3910
+ const title = collapseNewlines(storyTitle);
3905
3911
  return {
3906
3912
  title,
3907
- stories: Object.entries(domSnapshots).map(([name, { viewport }]) => ({
3908
- name,
3909
- // Viewport addon (Storybook 10+): `parameters.viewport.options` registers sizes; `globals.viewport`
3910
- // selects the active one. See https://storybook.js.org/docs/essentials/viewport#defining-the-viewport-for-a-story
3911
- // `defaultViewport` is not read by SB 10's types but our archive preview uses it as a fetch fallback.
3912
- globals: {
3913
- viewport: viewportToString(viewport)
3914
- },
3915
- parameters: {
3916
- server: {
3917
- id: snapshotId(title, name)
3918
- },
3919
- chromatic: {
3920
- ...chromaticStorybookParams,
3921
- modes: buildStoryModesConfig([
3922
- viewport
3923
- ])
3913
+ stories: Object.entries(domSnapshots).map(([snapshotName, { viewport }]) => {
3914
+ const name = collapseNewlines(snapshotName);
3915
+ return {
3916
+ name,
3917
+ // Viewport addon (Storybook 10+): `parameters.viewport.options` registers sizes; `globals.viewport`
3918
+ // selects the active one. See https://storybook.js.org/docs/essentials/viewport#defining-the-viewport-for-a-story
3919
+ // `defaultViewport` is not read by SB 10's types but our archive preview uses it as a fetch fallback.
3920
+ globals: {
3921
+ viewport: viewportToString(viewport)
3924
3922
  },
3925
- viewport: {
3926
- options: buildStoryViewportsConfig([
3927
- viewport
3928
- ]),
3929
- defaultViewport: viewportToString(findDefaultViewport([
3930
- viewport
3931
- ]))
3923
+ parameters: {
3924
+ // Work-around for cases where "あ" in story name would cause Storybook to fail to load the story due to an invalid story ID.
3925
+ // See https://github.com/chromaui/chromatic-e2e/issues/365
3926
+ __id: toId(title, storyNameFromExport(name)),
3927
+ server: {
3928
+ id: snapshotId(title, name)
3929
+ },
3930
+ chromatic: {
3931
+ ...chromaticStorybookParams,
3932
+ modes: buildStoryModesConfig([
3933
+ viewport
3934
+ ])
3935
+ },
3936
+ viewport: {
3937
+ options: buildStoryViewportsConfig([
3938
+ viewport
3939
+ ]),
3940
+ defaultViewport: viewportToString(findDefaultViewport([
3941
+ viewport
3942
+ ]))
3943
+ }
3932
3944
  }
3933
- }
3934
- }))
3945
+ };
3946
+ })
3935
3947
  };
3936
3948
  }
3937
3949
  __name(createStories, "createStories");
@@ -4041,7 +4053,7 @@ var DEFAULT_GLOBAL_RESOURCE_ARCHIVE_TIMEOUT_MS = 1e4;
4041
4053
 
4042
4054
  // src/node/commands.ts
4043
4055
  import assert from "node:assert";
4044
- import { resolve } from "node:path";
4056
+ import { resolve as resolve2 } from "node:path";
4045
4057
 
4046
4058
  // src/node/NetworkIdleTracker.ts
4047
4059
  var NetworkIdleTimeoutError = class NetworkIdleTimeoutError2 extends Error {
@@ -4085,9 +4097,9 @@ var NetworkIdleTracker = class _NetworkIdleTracker {
4085
4097
  if (this.pending.size === 0 && this.idleTimer === null) {
4086
4098
  return Promise.resolve();
4087
4099
  }
4088
- return new Promise((resolve3, reject) => {
4100
+ return new Promise((resolve4, reject) => {
4089
4101
  const timeout = setTimeout(() => reject(new NetworkIdleTimeoutError("Timed out waiting for network to be idle")), rejectTimeout);
4090
- this.idleResolvers.push(resolve3, () => clearTimeout(timeout));
4102
+ this.idleResolvers.push(resolve4, () => clearTimeout(timeout));
4091
4103
  });
4092
4104
  }
4093
4105
  onComplete = (params) => {
@@ -4115,6 +4127,128 @@ var NetworkIdleTracker = class _NetworkIdleTracker {
4115
4127
  }
4116
4128
  };
4117
4129
 
4130
+ // src/node/reporter.ts
4131
+ import { relative, resolve } from "node:path";
4132
+ import colors from "tinyrainbow";
4133
+
4134
+ // src/constants.ts
4135
+ var DEFAULT_OUTPUT_DIR = ".vitest/chromatic";
4136
+
4137
+ // src/node/reporter.ts
4138
+ var REPORTER_NAME = "chromatic-reporter";
4139
+ var ChromaticReporter = class _ChromaticReporter {
4140
+ static {
4141
+ __name(this, "ChromaticReporter");
4142
+ }
4143
+ ctx;
4144
+ options;
4145
+ snapshotCountPerEntity;
4146
+ name = REPORTER_NAME;
4147
+ constructor(ctx, options, snapshotCountPerEntity = /* @__PURE__ */ new Map()) {
4148
+ this.ctx = ctx;
4149
+ this.options = options;
4150
+ this.snapshotCountPerEntity = snapshotCountPerEntity;
4151
+ }
4152
+ /**
4153
+ * Add `ChromaticReporter` to Vitest reporters unless it's already included.
4154
+ */
4155
+ static apply(ctx, pluginOptions) {
4156
+ const options = {
4157
+ verbose: pluginOptions.reporter.verbose,
4158
+ outputDirectory: pluginOptions.outputDirectory,
4159
+ builtInReporter: "default"
4160
+ };
4161
+ for (const reporter of ctx.config.reporters) {
4162
+ if (isChromaticReporter(reporter)) {
4163
+ return;
4164
+ }
4165
+ if (!Array.isArray(reporter)) {
4166
+ continue;
4167
+ }
4168
+ const reporterName = reporter[0];
4169
+ if (reporterName === "tree" || reporterName === "default" || reporterName === "verbose") {
4170
+ options.builtInReporter = reporterName;
4171
+ }
4172
+ }
4173
+ ctx.config.reporters.push(new _ChromaticReporter(ctx, options));
4174
+ }
4175
+ /**
4176
+ * Custom reporter life-cycle called when `takeSnapshot()` is called.
4177
+ */
4178
+ static onSnapshot(ctx, test) {
4179
+ const reporter = ctx.config.reporters.find(isChromaticReporter);
4180
+ reporter?._onSnapshot(test);
4181
+ }
4182
+ onTestCaseResult(testCase) {
4183
+ if (this.options.builtInReporter !== "verbose") {
4184
+ return;
4185
+ }
4186
+ this.logSnapshots({
4187
+ count: this.snapshotCountPerEntity.get(testCase.id) ?? 0,
4188
+ indentation: 3,
4189
+ projectName: testCase.project.name
4190
+ });
4191
+ }
4192
+ onTestModuleEnd(testModule) {
4193
+ if (this.options.builtInReporter !== "default" && this.options.builtInReporter !== "tree") {
4194
+ return;
4195
+ }
4196
+ this.logSnapshots({
4197
+ count: this.snapshotCountPerEntity.get(testModule.id) ?? 0,
4198
+ indentation: this.options.builtInReporter === "default" ? 3 : 2,
4199
+ projectName: this.options.builtInReporter === "default" && testModule.project.name
4200
+ });
4201
+ }
4202
+ onTestRunEnd() {
4203
+ const snapshotCount = [
4204
+ ...this.snapshotCountPerEntity.values()
4205
+ ].reduce((a, b) => a + b, 0);
4206
+ this.snapshotCountPerEntity.clear();
4207
+ if (snapshotCount === 0) {
4208
+ return;
4209
+ }
4210
+ const output = resolve(this.ctx.config.root, this.options.outputDirectory);
4211
+ const separator = colors.dim("\u2500".repeat(this.ctx.logger.getColumns()));
4212
+ let uploadCommand = "chromatic --vitest --project-token=<TOKEN>";
4213
+ if (this.options.outputDirectory !== DEFAULT_OUTPUT_DIR || this.ctx.config.root !== process.cwd()) {
4214
+ uploadCommand = `CHROMATIC_ARCHIVE_LOCATION=${relative(process.cwd(), output)} ${uploadCommand}`;
4215
+ }
4216
+ this.ctx.logger.log(`${separator}`, `
4217
+ ${colors.inverse(" Chromatic Visual Regression ")}`, `
4218
+
4219
+ ${colors.green("\u2713")} ${snapshotCount} ${pluralize(snapshotCount, "archive")} captured`, `
4220
+
4221
+ Archives saved in ${colors.dim(output)}`, `
4222
+ To upload archives into Chromatic run ${colors.green(uploadCommand)}`, `
4223
+
4224
+ ${separator}
4225
+ `);
4226
+ }
4227
+ logSnapshots(options) {
4228
+ if (!this.options.verbose || options.count === 0) {
4229
+ return;
4230
+ }
4231
+ const snapshots = `(${options.count} ${pluralize(options.count, "archive")} captured)`;
4232
+ if (options.projectName) {
4233
+ options.indentation += options.projectName.length + 2;
4234
+ }
4235
+ this.ctx.logger.log(`${" ".repeat(options.indentation)} ${colors.dim(snapshots)}`);
4236
+ }
4237
+ _onSnapshot(test) {
4238
+ const key = this.options.builtInReporter === "verbose" ? test.id : test.module.id;
4239
+ const previousCount = this.snapshotCountPerEntity.get(key) ?? 0;
4240
+ this.snapshotCountPerEntity.set(key, previousCount + 1);
4241
+ }
4242
+ };
4243
+ function isChromaticReporter(reporter) {
4244
+ return "name" in reporter && reporter.name === REPORTER_NAME;
4245
+ }
4246
+ __name(isChromaticReporter, "isChromaticReporter");
4247
+ function pluralize(count, text) {
4248
+ return count === 1 ? text : `${text}s`;
4249
+ }
4250
+ __name(pluralize, "pluralize");
4251
+
4118
4252
  // src/node/commands.ts
4119
4253
  function createCommands(options) {
4120
4254
  const resourceArchivers = /* @__PURE__ */ new Map();
@@ -4133,6 +4267,8 @@ function createCommands(options) {
4133
4267
  * Can be called multiple times during a single test case.
4134
4268
  */
4135
4269
  async __chromatic_uploadDOMSnapshot(context, id, snapshot, pseudoClassIds, name) {
4270
+ const entity = context.project.vitest.state.getReportedEntityById(id);
4271
+ assert(entity?.type === "test", `Expected entity with id ${id} to be a test, found ${entity?.type}`);
4136
4272
  let sessionSnapshots = snapshots.get(id);
4137
4273
  if (!sessionSnapshots) {
4138
4274
  sessionSnapshots = /* @__PURE__ */ new Map();
@@ -4149,6 +4285,7 @@ function createCommands(options) {
4149
4285
  viewport,
4150
4286
  pseudoClassIds
4151
4287
  });
4288
+ ChromaticReporter.onSnapshot(context.project.vitest, entity);
4152
4289
  },
4153
4290
  /**
4154
4291
  * Wait for network to be idle, meaning no new network requests for at least `idleNetworkInterval` ms.
@@ -4182,16 +4319,19 @@ function createCommands(options) {
4182
4319
  assert(sessionSnapshots, `No snapshots found for test ${id}`);
4183
4320
  const snapshotBuffers = {};
4184
4321
  for (const [name, { snapshot, viewport, pseudoClassIds }] of sessionSnapshots) {
4185
- snapshotBuffers[name] = {
4322
+ const names = getSnapshotPrefix(entity).concat(name).join(" / ");
4323
+ snapshotBuffers[names] = {
4186
4324
  snapshot: Buffer.from(JSON.stringify(snapshot)),
4187
4325
  viewport,
4188
4326
  pseudoClassIds
4189
4327
  };
4190
4328
  }
4191
4329
  await writeTestResult({
4192
- outputDir: resolve(context.project.vitest.config.root, options.outputDirectory),
4330
+ outputDir: resolve2(context.project.vitest.config.root, options.outputDirectory),
4193
4331
  pageUrl: context.page.url(),
4194
- titlePath: getNames(entity)
4332
+ titlePath: testOptions.title ? [
4333
+ testOptions.title
4334
+ ] : getTitle(entity)
4195
4335
  }, snapshotBuffers, archive, {
4196
4336
  delay: testOptions.delay ?? options.delay,
4197
4337
  diffIncludeAntiAliasing: testOptions.diffIncludeAntiAliasing ?? options.diffIncludeAntiAliasing,
@@ -4243,7 +4383,18 @@ function createCommands(options) {
4243
4383
  __name(onTestCleanup, "onTestCleanup");
4244
4384
  }
4245
4385
  __name(createCommands, "createCommands");
4246
- function getNames(test) {
4386
+ function getTitle(test) {
4387
+ const names = [
4388
+ test.module.relativeModuleId
4389
+ ];
4390
+ const hasManyProjects = test.project.vitest.projects.filter((project) => project.config.browser.name === "chromium").length > 1;
4391
+ if (hasManyProjects && test.project.name) {
4392
+ names.unshift(test.project.name);
4393
+ }
4394
+ return names;
4395
+ }
4396
+ __name(getTitle, "getTitle");
4397
+ function getSnapshotPrefix(test) {
4247
4398
  const names = [
4248
4399
  test.name
4249
4400
  ];
@@ -4254,19 +4405,9 @@ function getNames(test) {
4254
4405
  names.unshift(current.name);
4255
4406
  }
4256
4407
  }
4257
- if (current.type === "module") {
4258
- names.unshift(current.relativeModuleId);
4259
- }
4260
- const hasManyProjects = test.project.vitest.projects.filter((project) => project.config.browser.name === "chromium").length > 1;
4261
- if (hasManyProjects && test.project.name) {
4262
- names.unshift(test.project.name);
4263
- }
4264
4408
  return names;
4265
4409
  }
4266
- __name(getNames, "getNames");
4267
-
4268
- // src/constants.ts
4269
- var DEFAULT_OUTPUT_DIR = ".vitest/chromatic";
4410
+ __name(getSnapshotPrefix, "getSnapshotPrefix");
4270
4411
 
4271
4412
  // src/node/plugin.ts
4272
4413
  var DEFAULT_TAG_DESCRIPTION = "Visual Regression Tests for `@chromatic-com/vitest`";
@@ -4277,10 +4418,11 @@ function chromaticPlugin(userOptions = {}) {
4277
4418
  outputDirectory: DEFAULT_OUTPUT_DIR,
4278
4419
  resourceArchiveTimeout: DEFAULT_GLOBAL_RESOURCE_ARCHIVE_TIMEOUT_MS,
4279
4420
  idleNetworkInterval: 100,
4280
- ...userOptions
4421
+ ...userOptions,
4422
+ reporter: resolveReporterOptions(userOptions.reporter)
4281
4423
  };
4282
4424
  const isDist = import.meta.url.includes("dist/plugin.js");
4283
- const setupFile = resolve2(import.meta.dirname, isDist ? "./setupFile.js" : "../browser/setupFile.ts");
4425
+ const setupFile = resolve3(import.meta.dirname, isDist ? "./setupFile.js" : "../browser/setupFile.ts");
4284
4426
  return {
4285
4427
  name: "vitest:chromatic",
4286
4428
  config() {
@@ -4304,16 +4446,19 @@ function chromaticPlugin(userOptions = {}) {
4304
4446
  if (!browser.enabled || browser.name !== "chromium") {
4305
4447
  return clean();
4306
4448
  }
4449
+ if (options.reporter.enabled) {
4450
+ ChromaticReporter.apply(context.vitest, options);
4451
+ }
4307
4452
  if (sequence.hooks === "stack") {
4308
4453
  project.config.setupFiles.push(setupFile);
4309
4454
  } else if (sequence.hooks === "list") {
4310
4455
  project.config.setupFiles.unshift(setupFile);
4311
4456
  } else {
4312
4457
  project.config.setupFiles.push(setupFile);
4313
- context.vitest.logger.warn(colors.bgYellow(colors.black(" chromatic ")), colors.yellow(`Using { sequence.hooks: 'parallel' } may cause unstable snapshots. Please set 'sequence.hooks' to 'list' or 'stack' to ensure reliable snapshot ordering.`));
4458
+ context.vitest.logger.warn(colors2.bgYellow(colors2.black(" chromatic ")), colors2.yellow(`Using { sequence.hooks: 'parallel' } may cause unstable snapshots. Please set 'sequence.hooks' to 'list' or 'stack' to ensure reliable snapshot ordering.`));
4314
4459
  }
4315
4460
  if (options.tags && context.vitest.version.startsWith("4.0")) {
4316
- context.vitest.logger.warn(colors.bgYellow(colors.black(" chromatic ")), colors.yellow(`Tags cannot be used with Vitest ${context.vitest.version}. Please upgrade to Vitest 4.1 or later to use this feature.`));
4461
+ context.vitest.logger.warn(colors2.bgYellow(colors2.black(" chromatic ")), colors2.yellow(`Tags cannot be used with Vitest ${context.vitest.version}. Please upgrade to Vitest 4.1 or later to use this feature.`));
4317
4462
  }
4318
4463
  if (options.tags) {
4319
4464
  project.config.tags ||= [];
@@ -4335,7 +4480,7 @@ function chromaticPlugin(userOptions = {}) {
4335
4480
  await project.browser?.triggerCommand("__chromatic_reset", {});
4336
4481
  });
4337
4482
  function clean() {
4338
- rmSync(resolve2(project.vitest.config.root, options.outputDirectory, "chromatic-archives"), {
4483
+ rmSync(resolve3(project.vitest.config.root, options.outputDirectory, "chromatic-archives"), {
4339
4484
  recursive: true,
4340
4485
  force: true
4341
4486
  });
@@ -4345,6 +4490,25 @@ function chromaticPlugin(userOptions = {}) {
4345
4490
  };
4346
4491
  }
4347
4492
  __name(chromaticPlugin, "chromaticPlugin");
4493
+ function resolveReporterOptions(reporter) {
4494
+ if (reporter == void 0 || reporter === true) {
4495
+ return {
4496
+ enabled: true,
4497
+ verbose: true
4498
+ };
4499
+ }
4500
+ if (reporter === false) {
4501
+ return {
4502
+ enabled: false,
4503
+ verbose: false
4504
+ };
4505
+ }
4506
+ return {
4507
+ enabled: reporter.enabled ?? true,
4508
+ verbose: reporter.verbose ?? true
4509
+ };
4510
+ }
4511
+ __name(resolveReporterOptions, "resolveReporterOptions");
4348
4512
  export {
4349
4513
  chromaticPlugin
4350
4514
  };
package/dist/setupFile.js CHANGED
@@ -143,6 +143,7 @@ beforeEach(async ({ task }) => {
143
143
  task.meta.__chromatic_isRegistered = true;
144
144
  task.meta.__chromatic_isTakeSnapshotCalled = false;
145
145
  task.meta.__chromatic_options ||= {};
146
+ task.meta.__chromatic_options.disableAutoSnapshot ??= options.disableAutoSnapshot;
146
147
  await commands3.__chromatic_interceptFetch(task.id);
147
148
  return /* @__PURE__ */ __name(async function beforeEachCleanup() {
148
149
  const { __chromatic_isTakeSnapshotCalled: isTakeSnapshotCalled, __chromatic_pendingTakeSnapshots: pendingTakeSnapshots, __chromatic_isRegistered: isRegistered } = task.meta;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chromatic-com/vitest",
3
- "version": "0.0.8",
3
+ "version": "0.0.10",
4
4
  "description": "Chromatic Visual Regression Testing for Vitest",
5
5
  "repository": {
6
6
  "type": "git",