@chromatic-com/vitest 0.0.9 → 0.1.0

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/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 : {
@@ -3799,8 +3799,7 @@ var DOMSnapshot = class {
3799
3799
  const currentSrc = this.mapSrcsetUrls(srcsetValue, sourceMap);
3800
3800
  if (currentSrc) {
3801
3801
  node.attributes.src = currentSrc;
3802
- delete node.attributes.srcset;
3803
- delete node.attributes.sizes;
3802
+ this.removeResponsiveImageAttributes(node.attributes);
3804
3803
  }
3805
3804
  }
3806
3805
  if (node.tagName === "picture") {
@@ -3825,6 +3824,7 @@ var DOMSnapshot = class {
3825
3824
  const imageElement = node.childNodes.find((childNode) => childNode.type === NodeType.Element && childNode.tagName === "img");
3826
3825
  if (imageElement && imageElement.attributes) {
3827
3826
  imageElement.attributes.src = sourceMap.get(matchingUrl);
3827
+ this.removeResponsiveImageAttributes(imageElement.attributes);
3828
3828
  }
3829
3829
  }
3830
3830
  }
@@ -3859,6 +3859,10 @@ var DOMSnapshot = class {
3859
3859
  });
3860
3860
  return currentSrc;
3861
3861
  }
3862
+ removeResponsiveImageAttributes(attributes) {
3863
+ delete attributes.srcset;
3864
+ delete attributes.sizes;
3865
+ }
3862
3866
  };
3863
3867
 
3864
3868
  // ../shared/src/utils/viewport.ts
@@ -3910,8 +3914,9 @@ function createStories(storyTitle, domSnapshots, chromaticStorybookParams) {
3910
3914
  const title = collapseNewlines(storyTitle);
3911
3915
  return {
3912
3916
  title,
3913
- stories: Object.entries(domSnapshots).map(([snapshotName, { viewport }]) => {
3917
+ stories: Object.entries(domSnapshots).map(([snapshotName, { viewport, parameters }]) => {
3914
3918
  const name = collapseNewlines(snapshotName);
3919
+ const { chromatic: chromaticParams, ...restParameters } = parameters || {};
3915
3920
  return {
3916
3921
  name,
3917
3922
  // Viewport addon (Storybook 10+): `parameters.viewport.options` registers sizes; `globals.viewport`
@@ -3929,6 +3934,7 @@ function createStories(storyTitle, domSnapshots, chromaticStorybookParams) {
3929
3934
  },
3930
3935
  chromatic: {
3931
3936
  ...chromaticStorybookParams,
3937
+ ...chromaticParams,
3932
3938
  modes: buildStoryModesConfig([
3933
3939
  viewport
3934
3940
  ])
@@ -3940,7 +3946,8 @@ function createStories(storyTitle, domSnapshots, chromaticStorybookParams) {
3940
3946
  defaultViewport: viewportToString(findDefaultViewport([
3941
3947
  viewport
3942
3948
  ]))
3943
- }
3949
+ },
3950
+ ...restParameters
3944
3951
  }
3945
3952
  };
3946
3953
  })
@@ -4053,7 +4060,7 @@ var DEFAULT_GLOBAL_RESOURCE_ARCHIVE_TIMEOUT_MS = 1e4;
4053
4060
 
4054
4061
  // src/node/commands.ts
4055
4062
  import assert from "node:assert";
4056
- import { resolve } from "node:path";
4063
+ import { resolve as resolve2 } from "node:path";
4057
4064
 
4058
4065
  // src/node/NetworkIdleTracker.ts
4059
4066
  var NetworkIdleTimeoutError = class NetworkIdleTimeoutError2 extends Error {
@@ -4097,9 +4104,9 @@ var NetworkIdleTracker = class _NetworkIdleTracker {
4097
4104
  if (this.pending.size === 0 && this.idleTimer === null) {
4098
4105
  return Promise.resolve();
4099
4106
  }
4100
- return new Promise((resolve3, reject) => {
4107
+ return new Promise((resolve4, reject) => {
4101
4108
  const timeout = setTimeout(() => reject(new NetworkIdleTimeoutError("Timed out waiting for network to be idle")), rejectTimeout);
4102
- this.idleResolvers.push(resolve3, () => clearTimeout(timeout));
4109
+ this.idleResolvers.push(resolve4, () => clearTimeout(timeout));
4103
4110
  });
4104
4111
  }
4105
4112
  onComplete = (params) => {
@@ -4127,6 +4134,128 @@ var NetworkIdleTracker = class _NetworkIdleTracker {
4127
4134
  }
4128
4135
  };
4129
4136
 
4137
+ // src/node/reporter.ts
4138
+ import { relative, resolve } from "node:path";
4139
+ import colors from "tinyrainbow";
4140
+
4141
+ // src/constants.ts
4142
+ var DEFAULT_OUTPUT_DIR = ".vitest/chromatic";
4143
+
4144
+ // src/node/reporter.ts
4145
+ var REPORTER_NAME = "chromatic-reporter";
4146
+ var ChromaticReporter = class _ChromaticReporter {
4147
+ static {
4148
+ __name(this, "ChromaticReporter");
4149
+ }
4150
+ ctx;
4151
+ options;
4152
+ snapshotCountPerEntity;
4153
+ name = REPORTER_NAME;
4154
+ constructor(ctx, options, snapshotCountPerEntity = /* @__PURE__ */ new Map()) {
4155
+ this.ctx = ctx;
4156
+ this.options = options;
4157
+ this.snapshotCountPerEntity = snapshotCountPerEntity;
4158
+ }
4159
+ /**
4160
+ * Add `ChromaticReporter` to Vitest reporters unless it's already included.
4161
+ */
4162
+ static apply(ctx, pluginOptions) {
4163
+ const options = {
4164
+ verbose: pluginOptions.reporter.verbose,
4165
+ outputDirectory: pluginOptions.outputDirectory,
4166
+ builtInReporter: "default"
4167
+ };
4168
+ for (const reporter of ctx.config.reporters) {
4169
+ if (isChromaticReporter(reporter)) {
4170
+ return;
4171
+ }
4172
+ if (!Array.isArray(reporter)) {
4173
+ continue;
4174
+ }
4175
+ const reporterName = reporter[0];
4176
+ if (reporterName === "tree" || reporterName === "default" || reporterName === "verbose") {
4177
+ options.builtInReporter = reporterName;
4178
+ }
4179
+ }
4180
+ ctx.config.reporters.push(new _ChromaticReporter(ctx, options));
4181
+ }
4182
+ /**
4183
+ * Custom reporter life-cycle called when `takeSnapshot()` is called.
4184
+ */
4185
+ static onSnapshot(ctx, test) {
4186
+ const reporter = ctx.config.reporters.find(isChromaticReporter);
4187
+ reporter?._onSnapshot(test);
4188
+ }
4189
+ onTestCaseResult(testCase) {
4190
+ if (this.options.builtInReporter !== "verbose") {
4191
+ return;
4192
+ }
4193
+ this.logSnapshots({
4194
+ count: this.snapshotCountPerEntity.get(testCase.id) ?? 0,
4195
+ indentation: 3,
4196
+ projectName: testCase.project.name
4197
+ });
4198
+ }
4199
+ onTestModuleEnd(testModule) {
4200
+ if (this.options.builtInReporter !== "default" && this.options.builtInReporter !== "tree") {
4201
+ return;
4202
+ }
4203
+ this.logSnapshots({
4204
+ count: this.snapshotCountPerEntity.get(testModule.id) ?? 0,
4205
+ indentation: this.options.builtInReporter === "default" ? 3 : 2,
4206
+ projectName: this.options.builtInReporter === "default" && testModule.project.name
4207
+ });
4208
+ }
4209
+ onTestRunEnd() {
4210
+ const snapshotCount = [
4211
+ ...this.snapshotCountPerEntity.values()
4212
+ ].reduce((a, b) => a + b, 0);
4213
+ this.snapshotCountPerEntity.clear();
4214
+ if (snapshotCount === 0) {
4215
+ return;
4216
+ }
4217
+ const output = resolve(this.ctx.config.root, this.options.outputDirectory);
4218
+ const separator = colors.dim("\u2500".repeat(this.ctx.logger.getColumns()));
4219
+ let uploadCommand = "chromatic --vitest --project-token=<TOKEN>";
4220
+ if (this.options.outputDirectory !== DEFAULT_OUTPUT_DIR || this.ctx.config.root !== process.cwd()) {
4221
+ uploadCommand = `CHROMATIC_ARCHIVE_LOCATION=${relative(process.cwd(), output)} ${uploadCommand}`;
4222
+ }
4223
+ this.ctx.logger.log(`${separator}`, `
4224
+ ${colors.inverse(" Chromatic Visual Regression ")}`, `
4225
+
4226
+ ${colors.green("\u2713")} ${snapshotCount} ${pluralize(snapshotCount, "archive")} captured`, `
4227
+
4228
+ Archives saved in ${colors.dim(output)}`, `
4229
+ To upload archives into Chromatic run ${colors.green(uploadCommand)}`, `
4230
+
4231
+ ${separator}
4232
+ `);
4233
+ }
4234
+ logSnapshots(options) {
4235
+ if (!this.options.verbose || options.count === 0) {
4236
+ return;
4237
+ }
4238
+ const snapshots = `(${options.count} ${pluralize(options.count, "archive")} captured)`;
4239
+ if (options.projectName) {
4240
+ options.indentation += options.projectName.length + 2;
4241
+ }
4242
+ this.ctx.logger.log(`${" ".repeat(options.indentation)} ${colors.dim(snapshots)}`);
4243
+ }
4244
+ _onSnapshot(test) {
4245
+ const key = this.options.builtInReporter === "verbose" ? test.id : test.module.id;
4246
+ const previousCount = this.snapshotCountPerEntity.get(key) ?? 0;
4247
+ this.snapshotCountPerEntity.set(key, previousCount + 1);
4248
+ }
4249
+ };
4250
+ function isChromaticReporter(reporter) {
4251
+ return "name" in reporter && reporter.name === REPORTER_NAME;
4252
+ }
4253
+ __name(isChromaticReporter, "isChromaticReporter");
4254
+ function pluralize(count, text) {
4255
+ return count === 1 ? text : `${text}s`;
4256
+ }
4257
+ __name(pluralize, "pluralize");
4258
+
4130
4259
  // src/node/commands.ts
4131
4260
  function createCommands(options) {
4132
4261
  const resourceArchivers = /* @__PURE__ */ new Map();
@@ -4145,6 +4274,8 @@ function createCommands(options) {
4145
4274
  * Can be called multiple times during a single test case.
4146
4275
  */
4147
4276
  async __chromatic_uploadDOMSnapshot(context, id, snapshot, pseudoClassIds, name) {
4277
+ const entity = context.project.vitest.state.getReportedEntityById(id);
4278
+ assert(entity?.type === "test", `Expected entity with id ${id} to be a test, found ${entity?.type}`);
4148
4279
  let sessionSnapshots = snapshots.get(id);
4149
4280
  if (!sessionSnapshots) {
4150
4281
  sessionSnapshots = /* @__PURE__ */ new Map();
@@ -4161,6 +4292,7 @@ function createCommands(options) {
4161
4292
  viewport,
4162
4293
  pseudoClassIds
4163
4294
  });
4295
+ ChromaticReporter.onSnapshot(context.project.vitest, entity);
4164
4296
  },
4165
4297
  /**
4166
4298
  * Wait for network to be idle, meaning no new network requests for at least `idleNetworkInterval` ms.
@@ -4198,11 +4330,20 @@ function createCommands(options) {
4198
4330
  snapshotBuffers[names] = {
4199
4331
  snapshot: Buffer.from(JSON.stringify(snapshot)),
4200
4332
  viewport,
4201
- pseudoClassIds
4333
+ pseudoClassIds,
4334
+ parameters: {
4335
+ chromatic: {
4336
+ vitest: {
4337
+ suites: getSuiteNames(entity),
4338
+ test: entity.name,
4339
+ snapshot: name
4340
+ }
4341
+ }
4342
+ }
4202
4343
  };
4203
4344
  }
4204
4345
  await writeTestResult({
4205
- outputDir: resolve(context.project.vitest.config.root, options.outputDirectory),
4346
+ outputDir: resolve2(context.project.vitest.config.root, options.outputDirectory),
4206
4347
  pageUrl: context.page.url(),
4207
4348
  titlePath: testOptions.title ? [
4208
4349
  testOptions.title
@@ -4260,7 +4401,7 @@ function createCommands(options) {
4260
4401
  __name(createCommands, "createCommands");
4261
4402
  function getTitle(test) {
4262
4403
  const names = [
4263
- test.module.relativeModuleId
4404
+ removeFileExtensions(test.module.relativeModuleId)
4264
4405
  ];
4265
4406
  const hasManyProjects = test.project.vitest.projects.filter((project) => project.config.browser.name === "chromium").length > 1;
4266
4407
  if (hasManyProjects && test.project.name) {
@@ -4283,9 +4424,30 @@ function getSnapshotPrefix(test) {
4283
4424
  return names;
4284
4425
  }
4285
4426
  __name(getSnapshotPrefix, "getSnapshotPrefix");
4286
-
4287
- // src/constants.ts
4288
- var DEFAULT_OUTPUT_DIR = ".vitest/chromatic";
4427
+ function getSuiteNames(test) {
4428
+ if (test.parent.type !== "suite") {
4429
+ return [];
4430
+ }
4431
+ const names = [];
4432
+ let current = test;
4433
+ while ("parent" in current && current.parent) {
4434
+ current = current.parent;
4435
+ if (current.type === "suite") {
4436
+ names.unshift(current.name);
4437
+ }
4438
+ }
4439
+ return names;
4440
+ }
4441
+ __name(getSuiteNames, "getSuiteNames");
4442
+ function removeFileExtensions(filepath) {
4443
+ const parts = filepath.split("/");
4444
+ const filename = parts.pop() || "";
4445
+ return parts.concat(
4446
+ // Trim filenames like "src/components/accordion/Accordion.browser.spec.tsx" -> "src/components/accordion/Accordion"
4447
+ filename.split(".")[0]
4448
+ ).join("/");
4449
+ }
4450
+ __name(removeFileExtensions, "removeFileExtensions");
4289
4451
 
4290
4452
  // src/node/plugin.ts
4291
4453
  var DEFAULT_TAG_DESCRIPTION = "Visual Regression Tests for `@chromatic-com/vitest`";
@@ -4296,10 +4458,11 @@ function chromaticPlugin(userOptions = {}) {
4296
4458
  outputDirectory: DEFAULT_OUTPUT_DIR,
4297
4459
  resourceArchiveTimeout: DEFAULT_GLOBAL_RESOURCE_ARCHIVE_TIMEOUT_MS,
4298
4460
  idleNetworkInterval: 100,
4299
- ...userOptions
4461
+ ...userOptions,
4462
+ reporter: resolveReporterOptions(userOptions.reporter)
4300
4463
  };
4301
4464
  const isDist = import.meta.url.includes("dist/plugin.js");
4302
- const setupFile = resolve2(import.meta.dirname, isDist ? "./setupFile.js" : "../browser/setupFile.ts");
4465
+ const setupFile = resolve3(import.meta.dirname, isDist ? "./setupFile.js" : "../browser/setupFile.ts");
4303
4466
  return {
4304
4467
  name: "vitest:chromatic",
4305
4468
  config() {
@@ -4323,16 +4486,19 @@ function chromaticPlugin(userOptions = {}) {
4323
4486
  if (!browser.enabled || browser.name !== "chromium") {
4324
4487
  return clean();
4325
4488
  }
4489
+ if (options.reporter.enabled) {
4490
+ ChromaticReporter.apply(context.vitest, options);
4491
+ }
4326
4492
  if (sequence.hooks === "stack") {
4327
4493
  project.config.setupFiles.push(setupFile);
4328
4494
  } else if (sequence.hooks === "list") {
4329
4495
  project.config.setupFiles.unshift(setupFile);
4330
4496
  } else {
4331
4497
  project.config.setupFiles.push(setupFile);
4332
- 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.`));
4498
+ 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.`));
4333
4499
  }
4334
4500
  if (options.tags && context.vitest.version.startsWith("4.0")) {
4335
- 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.`));
4501
+ 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.`));
4336
4502
  }
4337
4503
  if (options.tags) {
4338
4504
  project.config.tags ||= [];
@@ -4354,7 +4520,7 @@ function chromaticPlugin(userOptions = {}) {
4354
4520
  await project.browser?.triggerCommand("__chromatic_reset", {});
4355
4521
  });
4356
4522
  function clean() {
4357
- rmSync(resolve2(project.vitest.config.root, options.outputDirectory, "chromatic-archives"), {
4523
+ rmSync(resolve3(project.vitest.config.root, options.outputDirectory, "chromatic-archives"), {
4358
4524
  recursive: true,
4359
4525
  force: true
4360
4526
  });
@@ -4364,6 +4530,25 @@ function chromaticPlugin(userOptions = {}) {
4364
4530
  };
4365
4531
  }
4366
4532
  __name(chromaticPlugin, "chromaticPlugin");
4533
+ function resolveReporterOptions(reporter) {
4534
+ if (reporter == void 0 || reporter === true) {
4535
+ return {
4536
+ enabled: true,
4537
+ verbose: true
4538
+ };
4539
+ }
4540
+ if (reporter === false) {
4541
+ return {
4542
+ enabled: false,
4543
+ verbose: false
4544
+ };
4545
+ }
4546
+ return {
4547
+ enabled: reporter.enabled ?? true,
4548
+ verbose: reporter.verbose ?? true
4549
+ };
4550
+ }
4551
+ __name(resolveReporterOptions, "resolveReporterOptions");
4367
4552
  export {
4368
4553
  chromaticPlugin
4369
4554
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chromatic-com/vitest",
3
- "version": "0.0.9",
3
+ "version": "0.1.0",
4
4
  "description": "Chromatic Visual Regression Testing for Vitest",
5
5
  "repository": {
6
6
  "type": "git",