Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 44 additions & 1 deletion packages/vitest/src/command.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,17 @@ const TEST_PATH = "/project/src/Button.test.tsx";

import { createArgosScreenshotCommand } from "./command";

function createCtx() {
function createCtx(browserName = "chromium") {
const evaluate = vi.fn().mockResolvedValue(undefined);
const frame = { __brand: "frame" };
const ctx = {
page: { evaluate },
frame: vi.fn().mockResolvedValue(frame),
testPath: TEST_PATH,
// Each browser of `browser.instances` is a project of its own.
project: {
config: { browser: { name: browserName } },
},
} as unknown as BrowserCommandContext;
return { ctx, evaluate, frame };
}
Expand Down Expand Up @@ -204,4 +208,43 @@ describe("createArgosScreenshotCommand", () => {
// Attachments from every viewport are returned.
expect(attachments).toHaveLength(4);
});

it("adds the browser to the name and the baselines outside Chromium", async () => {
const command = createArgosScreenshotCommand();
const { ctx } = createCtx("firefox");

await command(ctx, "shot", { baseName: ["shot-variant", "shot"] });

const [, name, opts] = argosScreenshot.mock.calls[0]!;
expect(name).toBe("shot browser-[firefox]");
expect(opts.baseName).toEqual([
"shot-variant browser-[firefox]",
"shot browser-[firefox]",
]);
});

it("keeps the name and the baselines of Chromium", async () => {
const command = createArgosScreenshotCommand();
const { ctx } = createCtx("chromium");

await command(ctx, "shot", { baseName: "base" });

const [, name, opts] = argosScreenshot.mock.calls[0]!;
expect(name).toBe("shot");
expect(opts.baseName).toEqual(["base"]);
});

it("puts the browser before the viewport, in the name and the baselines", async () => {
const command = createArgosScreenshotCommand();
const { ctx } = createCtx("webkit");

await command(ctx, "resp", {
viewports: [{ width: 320, height: 480 }],
baseName: "base",
});

const [, name, opts] = argosScreenshot.mock.calls[0]!;
expect(name).toBe("resp browser-[webkit] vw-320");
expect(opts.baseName).toEqual(["base browser-[webkit] vw-320"]);
});
});
24 changes: 20 additions & 4 deletions packages/vitest/src/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ import {
type ArgosAttachment,
} from "@argos-ci/playwright";
import { resolveViewport, type ViewportSize } from "@argos-ci/browser";
import { getScreenshotName, normalizeBaseNames } from "@argos-ci/util";
import {
getBrowserSuffix,
getScreenshotName,
normalizeBaseNames,
} from "@argos-ci/util";
import type {
ArgosVitestPluginOptions,
VitestScreenshotOptions,
Expand Down Expand Up @@ -44,7 +48,14 @@ export const createArgosScreenshotCommand = (
}

const merged: ArgosVitestPluginOptions = { ...pluginOptions, ...options };
const baseNames = normalizeBaseNames(merged.baseName);
// Each browser of `browser.instances` is a project of its own, and writes
// to the same `root`: its name keeps the browsers from overwriting each
// other. Comes before the viewport suffix.
const browserSuffix = getBrowserSuffix(ctx.project.config.browser.name);
const screenshotName = `${name}${browserSuffix}`;
const baseNames = normalizeBaseNames(merged.baseName)?.map(
(baseName) => `${baseName}${browserSuffix}`,
);
const fullPage = merged.fullPage ?? false;
const fitWidth = !fullPage;

Expand Down Expand Up @@ -87,7 +98,7 @@ export const createArgosScreenshotCommand = (
setMetadata(size);
const shot = await screenshotFrame(
ctx,
getScreenshotName(name, { viewportWidth: size.width }),
getScreenshotName(screenshotName, { viewportWidth: size.width }),
{
...merged,
// The viewports loop is reimplemented here rather than delegated
Expand All @@ -106,7 +117,12 @@ export const createArgosScreenshotCommand = (
} else {
await setIframeViewportSize(ctx, "default", { fullPage });
setMetadata();
const shot = await screenshotFrame(ctx, name, merged, { fitWidth });
const shot = await screenshotFrame(
ctx,
screenshotName,
{ ...merged, baseName: baseNames },
{ fitWidth },
);
attachments.push(...shot);
}

Expand Down
35 changes: 23 additions & 12 deletions packages/vitest/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { ArgosAttachment } from "@argos-ci/playwright";
import { getBrowserSuffix } from "@argos-ci/util/browser";
import { resolveAutoName } from "./auto-name";
import { getCaptureMetadata, type TestMetadata } from "./metadata";
import type {
Expand All @@ -18,7 +19,8 @@ const METADATA_SUFFIX = ".argos.json";
* Characters reserved after a screenshot name when building its filename: the
* `` ` vw-<width>` `` viewport suffix, the largest capture extension
* (`.aria.yml`), and the metadata sidecar. Keeps auto-generated names within
* the filesystem limit.
* the filesystem limit. The browser suffix the Node command adds is reserved on
* top of it: `server.browser` is the `config.browser.name` it reads.
*/
const SCREENSHOT_NAME_RESERVED =
" vw-99999".length + ".aria.yml".length + METADATA_SUFFIX.length;
Expand Down Expand Up @@ -93,8 +95,14 @@ export async function argosScreenshot(
return [];
}

// Load vitest/browser using dynamic import to avoid loading it in non-Vitest
// environments.
const { server } = await import("vitest/browser");
const [resolvedName, { test, captureIndex, storybook }] = await Promise.all([
resolveAutoName(name, { reservedLength: SCREENSHOT_NAME_RESERVED }),
resolveAutoName(name, {
reservedLength:
SCREENSHOT_NAME_RESERVED + getBrowserSuffix(server.browser).length,
}),
// Gather the test metadata here (browser side), where the Vitest test
// context is available; it crosses the RPC boundary to the Node command.
getCaptureMetadata(),
Expand All @@ -103,9 +111,6 @@ export async function argosScreenshot(
warnIfStoriesUndetected();
}

// Load vitest/browser using dynamic import to avoid loading it in non-Vitest
// environments.
const { server } = await import("vitest/browser");
// Pass a defined `options` so the trailing `test` argument is never preceded
// by an `undefined` hole (which the browser/node RPC would drop).
return server.commands.argosScreenshot(
Expand Down Expand Up @@ -158,17 +163,26 @@ export async function argosSnapshot(
return [];
}

// Reserve room for the `.snapshot<ext>` suffix and the metadata sidecar so an
// Reserve room for the browser suffix the Node command adds (in browser
// mode), the `.snapshot<ext>` suffix and the metadata sidecar so an
// auto-generated filename stays within the filesystem limit. Kept in sync with
// `writeSnapshotFile` in `snapshot-file.ts`.
const rawExtension = options.extension ?? ".txt";
const extension = rawExtension.startsWith(".")
? rawExtension
: `.${rawExtension}`;
// Load vitest/browser using dynamic import to avoid loading it in non-Vitest
// environments.
const browserServer = checkIsBrowserEnv()
? (await import("vitest/browser")).server
: null;
const [resolvedName, { test, captureIndex, storybook }] = await Promise.all([
resolveAutoName(options.name, {
reservedLength:
".snapshot".length + extension.length + METADATA_SUFFIX.length,
".snapshot".length +
extension.length +
METADATA_SUFFIX.length +
getBrowserSuffix(browserServer?.browser).length,
}),
// Gather the test metadata here (browser or Node), where the Vitest test
// context is available.
Expand All @@ -191,11 +205,8 @@ export async function argosSnapshot(
...serializableOptions
} = options;

if (checkIsBrowserEnv()) {
// Load vitest/browser using dynamic import to avoid loading it in non-Vitest
// environments.
const { server } = await import("vitest/browser");
return server.commands.argosSnapshot(
if (browserServer) {
return browserServer.commands.argosSnapshot(
resolvedName,
serialized,
serializableOptions,
Expand Down
48 changes: 40 additions & 8 deletions packages/vitest/src/plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { createRequire } from "node:module";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { argosVitestPlugin } from "./plugin";
import { ArgosReporter, argosVitestPlugin } from "./plugin";

// The real implementation, unless a test simulates a missing package.
vi.mock("node:module", async (importOriginal) => {
Expand All @@ -23,15 +23,21 @@ afterEach(async () => {
await rm(root, { recursive: true, force: true });
});

/** Run the plugin's `configureVitest` hook, return the project setup files. */
/** Run the plugin's `configureVitest` hook for one project. */
function configureVitest(
plugin: ReturnType<typeof argosVitestPlugin>,
context: { vitest: unknown; project: unknown },
) {
(plugin.configureVitest as (context: unknown) => void)(context);
}

/** Configure a project, return its setup files. */
function configureProject(): string[] {
const plugin = argosVitestPlugin();
const project = { config: { root, setupFiles: [join(root, "setup.ts")] } };
const configureVitest = plugin.configureVitest as (context: {
vitest: unknown;
project: unknown;
}) => void;
configureVitest({ vitest: { config: { reporters: [] } }, project });
configureVitest(argosVitestPlugin(), {
vitest: { config: { reporters: [] } },
project,
});
return project.config.setupFiles;
}

Expand Down Expand Up @@ -59,4 +65,30 @@ describe("argosVitestPlugin", () => {
);
expect(configureProject()).toEqual([join(root, "setup.ts")]);
});

it("adds a single reporter, whatever the number of browser instances", () => {
const plugin = argosVitestPlugin({ uploadToArgos: true });
const vitest = { config: { reporters: ["default"] as unknown[] } };
// Each browser of `browser.instances` is a project of its own.
for (const browser of ["chromium", "firefox", "webkit"]) {
configureVitest(plugin, {
vitest,
project: {
config: { root, setupFiles: [], browser: { name: browser } },
},
});
}
expect(vitest.config.reporters).toHaveLength(2);
expect(vitest.config.reporters[0]).toBe("default");
expect(vitest.config.reporters[1]).toBeInstanceOf(ArgosReporter);
});

it("adds no reporter without uploadToArgos", () => {
const vitest = { config: { reporters: [] as unknown[] } };
configureVitest(argosVitestPlugin(), {
vitest,
project: { config: { root, setupFiles: [] } },
});
expect(vitest.config.reporters).toEqual([]);
});
});
12 changes: 8 additions & 4 deletions packages/vitest/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@ export function argosVitestPlugin(options?: ArgosVitestPluginOptions): Plugin {
dirname(fileURLToPath(import.meta.url)),
"./storybook-setup-file.mjs",
);
// A single reporter for the whole run: it uploads everything in `root`.
const reporter = uploadToArgos
? new ArgosReporter({ ...otherOptions, root })
: null;
return {
name: "@argos-ci/vitest",
configureVitest({ vitest, project }) {
Expand All @@ -88,10 +92,10 @@ export function argosVitestPlugin(options?: ArgosVitestPluginOptions): Plugin {
project.config.setupFiles.unshift(storybookSetupFile);
}

if (uploadToArgos) {
vitest.config.reporters.push(
new ArgosReporter({ ...otherOptions, root }),
);
// The hook runs for every project, including each browser of
// `browser.instances`: add the reporter once, or it uploads once each.
if (reporter && !vitest.config.reporters.includes(reporter)) {
vitest.config.reporters.push(reporter);
}
},
config() {
Expand Down
22 changes: 21 additions & 1 deletion packages/vitest/src/snapshot-command.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,14 @@ vi.mock("./snapshot-file", () => ({ writeSnapshotFile }));

import { createArgosSnapshotCommand } from "./snapshot-command";

const ctx = {} as BrowserCommandContext;
/** Context of a command run by the project of a `browser.instances` entry. */
function createCtx(browserName: string): BrowserCommandContext {
return {
project: { config: { browser: { name: browserName } } },
} as unknown as BrowserCommandContext;
}

const ctx = createCtx("chromium");

describe("createArgosSnapshotCommand", () => {
beforeEach(() => {
Expand Down Expand Up @@ -96,4 +103,17 @@ describe("createArgosSnapshotCommand", () => {
storybook,
);
});

it("adds the browser to the name outside Chromium", async () => {
const command = createArgosSnapshotCommand({ root: "/abs/screenshots" });
await command(createCtx("firefox"), "user", "serialized");
expect(writeSnapshotFile).toHaveBeenCalledWith(
"user browser-[firefox]",
"serialized",
{ root: "/abs/screenshots" },
undefined,
undefined,
undefined,
);
});
});
8 changes: 6 additions & 2 deletions packages/vitest/src/snapshot-command.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { BrowserCommand } from "vitest/node";
import type { ArgosAttachment } from "@argos-ci/playwright";
import { getBrowserSuffix } from "@argos-ci/util";
import type { TestMetadata } from "./metadata";
import type {
ArgosVitestPluginOptions,
Expand Down Expand Up @@ -31,7 +32,7 @@ export const createArgosSnapshotCommand = (
pluginOptions: ArgosVitestPluginOptions = {},
): BrowserCommand<ArgosSnapshotCommandArgs> => {
return async (
_ctx,
ctx,
name,
content,
options,
Expand All @@ -46,8 +47,11 @@ export const createArgosSnapshotCommand = (
root: pluginOptions.root,
...options,
};
// Same as screenshots: each browser of `browser.instances` writes to the
// same `root`, and would overwrite the snapshots of the others.
const browserSuffix = getBrowserSuffix(ctx.project.config.browser.name);
return writeSnapshotFile(
name,
`${name}${browserSuffix}`,
content,
merged,
test,
Expand Down
Loading