@chromatic-com/vitest 0.0.10 → 0.1.1

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.js CHANGED
@@ -154,7 +154,7 @@ async function waitForIdleNetwork(timeout) {
154
154
  throw new TypeError(`waitForIdleNetwork() cannot be called in a test that is not registered for Chromatic plugin.
155
155
  Make sure ${test.file.projectName || "root"} project has chromaticPlugin() enabled.`);
156
156
  }
157
- return await commands2.__chromatic_waitForIdleNetwork(test.id, timeout);
157
+ return await commands2.__chromatic_waitForIdleNetwork(timeout);
158
158
  }
159
159
  __name(waitForIdleNetwork, "waitForIdleNetwork");
160
160
  export {
package/dist/plugin.js CHANGED
@@ -3406,9 +3406,10 @@ var ResourceArchiver = class {
3406
3406
  * Currently active requests
3407
3407
  */
3408
3408
  pendingRequests = /* @__PURE__ */ new Set();
3409
- constructor(cdpClient, allowedDomains, httpCredentials) {
3409
+ constructor(cdpClient, allowedDomains, httpCredentials, firstUrl) {
3410
3410
  this.client = cdpClient;
3411
3411
  this.httpCredentials = httpCredentials;
3412
+ this.firstUrl = firstUrl;
3412
3413
  this.assetDomains = (allowedDomains || []).map((domain) => {
3413
3414
  if (domain.startsWith("http")) {
3414
3415
  return domain;
@@ -3518,12 +3519,25 @@ var ResourceArchiver = class {
3518
3519
  const contentTypeHeader = responseHeaders.find(({ name }) => name.toLowerCase() === "content-type");
3519
3520
  const isFirstRequest = requestUrl.toString() === this.firstUrl.toString();
3520
3521
  if (isRequestFromAllowedDomain && !isFirstRequest) {
3522
+ logger.log("Archiving request", {
3523
+ url: request.url,
3524
+ statusCode: responseStatusCode,
3525
+ statusText: responseStatusText,
3526
+ contentType: contentTypeHeader?.value
3527
+ });
3521
3528
  this.archive[request.url] = {
3522
3529
  statusCode: responseStatusCode,
3523
3530
  statusText: responseStatusText,
3524
3531
  body: Buffer.from(body, base64Encoded ? "base64" : "utf8"),
3525
3532
  contentType: contentTypeHeader?.value
3526
3533
  };
3534
+ } else {
3535
+ logger.log("Skipping archiving of request", {
3536
+ url: request.url,
3537
+ firstUrl: this.firstUrl.toString(),
3538
+ isFirstRequest,
3539
+ isRequestFromAllowedDomain
3540
+ });
3527
3541
  }
3528
3542
  await this.clientSend(request, "Fetch.continueRequest", {
3529
3543
  requestId
@@ -3533,6 +3547,7 @@ var ResourceArchiver = class {
3533
3547
 
3534
3548
  // ../shared/src/write-archive/index.ts
3535
3549
  import { join } from "node:path";
3550
+ import { existsSync as existsSync2 } from "node:fs";
3536
3551
 
3537
3552
  // ../shared/src/utils/filePaths.ts
3538
3553
  import { existsSync, mkdirSync } from "fs";
@@ -3799,8 +3814,7 @@ var DOMSnapshot = class {
3799
3814
  const currentSrc = this.mapSrcsetUrls(srcsetValue, sourceMap);
3800
3815
  if (currentSrc) {
3801
3816
  node.attributes.src = currentSrc;
3802
- delete node.attributes.srcset;
3803
- delete node.attributes.sizes;
3817
+ this.removeResponsiveImageAttributes(node.attributes);
3804
3818
  }
3805
3819
  }
3806
3820
  if (node.tagName === "picture") {
@@ -3825,6 +3839,7 @@ var DOMSnapshot = class {
3825
3839
  const imageElement = node.childNodes.find((childNode) => childNode.type === NodeType.Element && childNode.tagName === "img");
3826
3840
  if (imageElement && imageElement.attributes) {
3827
3841
  imageElement.attributes.src = sourceMap.get(matchingUrl);
3842
+ this.removeResponsiveImageAttributes(imageElement.attributes);
3828
3843
  }
3829
3844
  }
3830
3845
  }
@@ -3859,6 +3874,10 @@ var DOMSnapshot = class {
3859
3874
  });
3860
3875
  return currentSrc;
3861
3876
  }
3877
+ removeResponsiveImageAttributes(attributes) {
3878
+ delete attributes.srcset;
3879
+ delete attributes.sizes;
3880
+ }
3862
3881
  };
3863
3882
 
3864
3883
  // ../shared/src/utils/viewport.ts
@@ -3910,8 +3929,9 @@ function createStories(storyTitle, domSnapshots, chromaticStorybookParams) {
3910
3929
  const title = collapseNewlines(storyTitle);
3911
3930
  return {
3912
3931
  title,
3913
- stories: Object.entries(domSnapshots).map(([snapshotName, { viewport }]) => {
3932
+ stories: Object.entries(domSnapshots).map(([snapshotName, { viewport, parameters }]) => {
3914
3933
  const name = collapseNewlines(snapshotName);
3934
+ const { chromatic: chromaticParams, ...restParameters } = parameters || {};
3915
3935
  return {
3916
3936
  name,
3917
3937
  // Viewport addon (Storybook 10+): `parameters.viewport.options` registers sizes; `globals.viewport`
@@ -3929,6 +3949,7 @@ function createStories(storyTitle, domSnapshots, chromaticStorybookParams) {
3929
3949
  },
3930
3950
  chromatic: {
3931
3951
  ...chromaticStorybookParams,
3952
+ ...chromaticParams,
3932
3953
  modes: buildStoryModesConfig([
3933
3954
  viewport
3934
3955
  ])
@@ -3940,7 +3961,8 @@ function createStories(storyTitle, domSnapshots, chromaticStorybookParams) {
3940
3961
  defaultViewport: viewportToString(findDefaultViewport([
3941
3962
  viewport
3942
3963
  ]))
3943
- }
3964
+ },
3965
+ ...restParameters
3944
3966
  }
3945
3967
  };
3946
3968
  })
@@ -4018,10 +4040,13 @@ async function writeTestResult(e2eTestInfo, domSnapshots, archive, chromaticStor
4018
4040
  const archiveFile = new ArchiveFile(url, response, pageUrl);
4019
4041
  const origSrcPath = archiveFile.originalSrc();
4020
4042
  const fileSystemPath = archiveFile.toFileSystemPath();
4043
+ const responsePath = join(archiveDir, fileSystemPath);
4021
4044
  if (origSrcPath !== fileSystemPath) {
4022
4045
  sourceMap.set(origSrcPath, fileSystemPath);
4023
4046
  }
4024
- await outputFile(join(archiveDir, fileSystemPath), response.body);
4047
+ if (!existsSync2(responsePath)) {
4048
+ await outputFile(responsePath, response.body);
4049
+ }
4025
4050
  }));
4026
4051
  await Promise.all(Object.entries(domSnapshots).map(async ([name, domSnapshot]) => {
4027
4052
  const snapshot = new DOMSnapshot(domSnapshot);
@@ -4077,7 +4102,6 @@ var NetworkIdleTracker = class _NetworkIdleTracker {
4077
4102
  }
4078
4103
  static async create(cdp, idleTimeout) {
4079
4104
  const tracker = new _NetworkIdleTracker(cdp, idleTimeout);
4080
- await tracker.watch();
4081
4105
  return tracker;
4082
4106
  }
4083
4107
  async watch() {
@@ -4086,7 +4110,7 @@ var NetworkIdleTracker = class _NetworkIdleTracker {
4086
4110
  this.cdp.on("Network.loadingFailed", this.onComplete);
4087
4111
  await this.cdp.send("Network.enable");
4088
4112
  }
4089
- async off() {
4113
+ async unwatch() {
4090
4114
  this.cdp.off("Network.requestWillBeSent", this.onRequest);
4091
4115
  this.cdp.off("Network.loadingFinished", this.onComplete);
4092
4116
  this.cdp.off("Network.loadingFailed", this.onComplete);
@@ -4291,22 +4315,33 @@ function createCommands(options) {
4291
4315
  * Wait for network to be idle, meaning no new network requests for at least `idleNetworkInterval` ms.
4292
4316
  * Use `timeout` argument to reject if network doesn't become idle within given time.
4293
4317
  */
4294
- async __chromatic_waitForIdleNetwork(_, id, timeout) {
4295
- const networkIdleTracker = networkIdleTrackers.get(id);
4296
- assert(networkIdleTracker, `No network idle tracker found for test ${id}`);
4318
+ async __chromatic_waitForIdleNetwork(context, timeout) {
4319
+ const networkIdleTracker = networkIdleTrackers.get(context.sessionId);
4320
+ assert(networkIdleTracker, `No network idle tracker found for session ${context.sessionId}`);
4297
4321
  await networkIdleTracker.waitForIdle(timeout);
4298
4322
  },
4299
4323
  /**
4300
4324
  * Start recording HTTP resources and network activity for given test.
4301
4325
  */
4302
- async __chromatic_interceptFetch(context, id) {
4303
- const cdp = await context.provider.getCDPSession?.(context.sessionId);
4304
- assert(cdp, `Unable to get CDP session for session ${context.sessionId}`);
4305
- const { contextOptions } = context.project.config.browser.provider?.options ?? {};
4306
- const resourceArchiver = new ResourceArchiver(cdp, options.assetDomains, contextOptions?.httpCredentials);
4307
- resourceArchivers.set(id, resourceArchiver);
4326
+ async __chromatic_interceptFetch(context) {
4327
+ let resourceArchiver = resourceArchivers.get(context.sessionId);
4328
+ let networkIdleTracker = networkIdleTrackers.get(context.sessionId);
4329
+ let cdp;
4330
+ if (!resourceArchiver || !networkIdleTracker) {
4331
+ cdp = await context.provider.getCDPSession?.(context.sessionId);
4332
+ assert(cdp, `Unable to get CDP session for session ${context.sessionId}`);
4333
+ }
4334
+ if (!resourceArchiver) {
4335
+ const { contextOptions } = context.project.config.browser.provider?.options ?? {};
4336
+ resourceArchiver = new ResourceArchiver(cdp, options.assetDomains, contextOptions?.httpCredentials, new URL(context.page.url()));
4337
+ resourceArchivers.set(context.sessionId, resourceArchiver);
4338
+ }
4339
+ if (!networkIdleTracker) {
4340
+ networkIdleTracker = await NetworkIdleTracker.create(cdp, options.idleNetworkInterval);
4341
+ networkIdleTrackers.set(context.sessionId, networkIdleTracker);
4342
+ }
4343
+ await networkIdleTracker.watch();
4308
4344
  await resourceArchiver.watch();
4309
- networkIdleTrackers.set(id, await NetworkIdleTracker.create(cdp, options.idleNetworkInterval));
4310
4345
  },
4311
4346
  /**
4312
4347
  * Write captured snapshots and network resources to disk.
@@ -4315,7 +4350,7 @@ function createCommands(options) {
4315
4350
  async __chromatic_writeTestResult(context, id, testOptions = {}) {
4316
4351
  const entity = context.project.vitest.state.getReportedEntityById(id);
4317
4352
  assert(entity?.type === "test", `Expected entity with id ${id} to be a test, found ${entity?.type}`);
4318
- const { archive, sessionSnapshots } = await onTestCleanup(id);
4353
+ const { archive, sessionSnapshots } = await onTestCleanup(context, id);
4319
4354
  assert(sessionSnapshots, `No snapshots found for test ${id}`);
4320
4355
  const snapshotBuffers = {};
4321
4356
  for (const [name, { snapshot, viewport, pseudoClassIds }] of sessionSnapshots) {
@@ -4323,7 +4358,16 @@ function createCommands(options) {
4323
4358
  snapshotBuffers[names] = {
4324
4359
  snapshot: Buffer.from(JSON.stringify(snapshot)),
4325
4360
  viewport,
4326
- pseudoClassIds
4361
+ pseudoClassIds,
4362
+ parameters: {
4363
+ chromatic: {
4364
+ vitest: {
4365
+ suites: getSuiteNames(entity),
4366
+ test: entity.name,
4367
+ snapshot: name
4368
+ }
4369
+ }
4370
+ }
4327
4371
  };
4328
4372
  }
4329
4373
  await writeTestResult({
@@ -4346,13 +4390,16 @@ function createCommands(options) {
4346
4390
  /**
4347
4391
  * Clear test state without writing test results.
4348
4392
  */
4349
- async __chromatic_stopWithoutSnapshots(_, id) {
4350
- await onTestCleanup(id);
4393
+ async __chromatic_stopWithoutSnapshots(context, id) {
4394
+ await onTestCleanup(context, id);
4351
4395
  },
4352
4396
  /**
4353
4397
  * Reset all state of the plugin. Should be called between test runs.
4354
4398
  */
4355
4399
  async __chromatic_reset() {
4400
+ for (const resourceArchiver of resourceArchivers.values()) {
4401
+ resourceArchiver.archive = {};
4402
+ }
4356
4403
  resourceArchivers.clear();
4357
4404
  networkIdleTrackers.clear();
4358
4405
  snapshots.clear();
@@ -4365,14 +4412,13 @@ function createCommands(options) {
4365
4412
  return Object.fromEntries(snapshots.get(id) || []);
4366
4413
  }
4367
4414
  };
4368
- async function onTestCleanup(id) {
4369
- const resourceArchiver = resourceArchivers.get(id);
4415
+ async function onTestCleanup(context, id) {
4416
+ const resourceArchiver = resourceArchivers.get(context.sessionId);
4370
4417
  assert(resourceArchiver, `No resource archiver found for test ${id}`);
4371
- resourceArchivers.delete(id);
4418
+ const networkIdleTracker = networkIdleTrackers.get(context.sessionId);
4419
+ assert(networkIdleTracker, `No network idle tracker found for test ${id}`);
4372
4420
  await resourceArchiver.unwatch();
4373
- const networkIdleTracker = networkIdleTrackers.get(id);
4374
- networkIdleTrackers.delete(id);
4375
- await networkIdleTracker?.off();
4421
+ await networkIdleTracker.unwatch();
4376
4422
  const sessionSnapshots = snapshots.get(id);
4377
4423
  snapshots.delete(id);
4378
4424
  return {
@@ -4385,7 +4431,7 @@ function createCommands(options) {
4385
4431
  __name(createCommands, "createCommands");
4386
4432
  function getTitle(test) {
4387
4433
  const names = [
4388
- test.module.relativeModuleId
4434
+ removeFileExtensions(test.module.relativeModuleId)
4389
4435
  ];
4390
4436
  const hasManyProjects = test.project.vitest.projects.filter((project) => project.config.browser.name === "chromium").length > 1;
4391
4437
  if (hasManyProjects && test.project.name) {
@@ -4408,6 +4454,30 @@ function getSnapshotPrefix(test) {
4408
4454
  return names;
4409
4455
  }
4410
4456
  __name(getSnapshotPrefix, "getSnapshotPrefix");
4457
+ function getSuiteNames(test) {
4458
+ if (test.parent.type !== "suite") {
4459
+ return [];
4460
+ }
4461
+ const names = [];
4462
+ let current = test;
4463
+ while ("parent" in current && current.parent) {
4464
+ current = current.parent;
4465
+ if (current.type === "suite") {
4466
+ names.unshift(current.name);
4467
+ }
4468
+ }
4469
+ return names;
4470
+ }
4471
+ __name(getSuiteNames, "getSuiteNames");
4472
+ function removeFileExtensions(filepath) {
4473
+ const parts = filepath.split("/");
4474
+ const filename = parts.pop() || "";
4475
+ return parts.concat(
4476
+ // Trim filenames like "src/components/accordion/Accordion.browser.spec.tsx" -> "src/components/accordion/Accordion"
4477
+ filename.split(".")[0]
4478
+ ).join("/");
4479
+ }
4480
+ __name(removeFileExtensions, "removeFileExtensions");
4411
4481
 
4412
4482
  // src/node/plugin.ts
4413
4483
  var DEFAULT_TAG_DESCRIPTION = "Visual Regression Tests for `@chromatic-com/vitest`";
package/dist/setupFile.js CHANGED
@@ -126,7 +126,7 @@ async function waitForIdleNetwork(timeout) {
126
126
  throw new TypeError(`waitForIdleNetwork() cannot be called in a test that is not registered for Chromatic plugin.
127
127
  Make sure ${test.file.projectName || "root"} project has chromaticPlugin() enabled.`);
128
128
  }
129
- return await commands2.__chromatic_waitForIdleNetwork(test.id, timeout);
129
+ return await commands2.__chromatic_waitForIdleNetwork(timeout);
130
130
  }
131
131
  __name(waitForIdleNetwork, "waitForIdleNetwork");
132
132
 
@@ -144,7 +144,7 @@ beforeEach(async ({ task }) => {
144
144
  task.meta.__chromatic_isTakeSnapshotCalled = false;
145
145
  task.meta.__chromatic_options ||= {};
146
146
  task.meta.__chromatic_options.disableAutoSnapshot ??= options.disableAutoSnapshot;
147
- await commands3.__chromatic_interceptFetch(task.id);
147
+ await commands3.__chromatic_interceptFetch();
148
148
  return /* @__PURE__ */ __name(async function beforeEachCleanup() {
149
149
  const { __chromatic_isTakeSnapshotCalled: isTakeSnapshotCalled, __chromatic_pendingTakeSnapshots: pendingTakeSnapshots, __chromatic_isRegistered: isRegistered } = task.meta;
150
150
  if (!isRegistered) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chromatic-com/vitest",
3
- "version": "0.0.10",
3
+ "version": "0.1.1",
4
4
  "description": "Chromatic Visual Regression Testing for Vitest",
5
5
  "repository": {
6
6
  "type": "git",