test: replace false-green checks with behavioral coverage (#6282)

* test: replace false-green checks with behavioral coverage

* test: complete behavior-focused audit coverage
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-18 03:16:25 +08:00
1 parent c7ab7aa6da
commit 74942bd190
91 files changed
+1891 -1391

No files matched your search

+3 -1
View File
@@ -55,7 +55,9 @@ describe("channel logos", () => {
expectFootprint(icon);
expect(fallback).toHaveClass("opacity-0");
expect(image).toHaveClass("opacity-100");
expect(image).not.toHaveClass("invert", "grayscale", "object-cover");
for (const className of ["invert", "grayscale", "object-cover"]) {
expect(image).not.toHaveClass(className);
}
expect(icon).toHaveClass(presentation.logoLayout === "tile" ? "bg-transparent" : "bg-white");
expect(image).toHaveClass(...(presentation.logoLayout === "tile" ? ["h-8", "w-8"] : ["h-6", "w-6"]));
});
+20 -5
View File
@@ -1,7 +1,9 @@
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { describe, expect, it } from "vitest";
import postcss from "postcss";
import tailwindcss from "tailwindcss";
import loadConfig from "tailwindcss/loadConfig";
import { describe, expect, it, vi } from "vitest";
import {
channelUiContribution,
@@ -34,9 +36,22 @@ describe("channel UI contributions", () => {
expect(channelUiOwner("wechat")).toBe("weixin");
});
it("includes channel-owned UI in Tailwind's production scan", () => {
const source = readFileSync(resolve(process.cwd(), "tailwind.config.js"), "utf8");
it("includes channel-owned UI in Tailwind's production scan", async () => {
vi.stubEnv("NODE_ENV", "production");
try {
const config = loadConfig(resolve(process.cwd(), "tailwind.config.js"));
const result = await postcss([tailwindcss(config)]).process("@tailwind utilities;", { from: undefined });
expect(source).toContain("../nanobot/channels/*/webui/**/*.{ts,tsx}");
// Linear's connecting indicator uses a channel-only arbitrary color.
let backgroundColor: string | undefined;
result.root.walkRules(".bg-\\[\\#5E6AD2\\]", (rule) => {
rule.walkDecls("background-color", (declaration) => {
backgroundColor = declaration.value;
});
});
expect(backgroundColor?.trim()).toBeTruthy();
} finally {
vi.unstubAllEnvs();
}
});
});
+4 -2
View File
@@ -17,10 +17,12 @@ describe("form control focus styles", () => {
"focus-visible:ring-inset",
"focus-visible:ring-ring/50",
);
expect(element).not.toHaveClass(
for (const className of [
"ring-offset-background",
"focus-visible:ring-ring",
"focus-visible:ring-offset-2",
);
]) {
expect(element).not.toHaveClass(className);
}
});
});
+22 -48
View File
@@ -1,6 +1,6 @@
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { runInNewContext } from "node:vm";
import { Window } from "happy-dom";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
@@ -339,43 +339,24 @@ const ACCIDENTALLY_SPANISH_SETTINGS_KEYS = [
"settings.oauth.signInHelp",
];
const INDEX_HTML = readFileSync(resolve(process.cwd(), "index.html"), "utf8");
const PREBOOT_SCRIPT = INDEX_HTML.match(
/<script>\s*(\(function \(\) \{\s*var localeKey = "nanobot\.locale";[\s\S]*?\}\)\(\);)\s*<\/script>/,
)?.[1];
const BOOT_COPY_MARKUP = '<span data-boot-copy>Loading nanobot…</span>';
function runPrebootLocale(storedLocale: string) {
if (!PREBOOT_SCRIPT) throw new Error("Could not find the preboot locale script in index.html");
const documentElement = { lang: "" };
const meta = {
content: "",
setAttribute(name: string, value: string) {
if (name === "content") this.content = value;
},
};
const boot = { textContent: "" };
runInNewContext(PREBOOT_SCRIPT, {
localStorage: {
getItem: (key: string) => key === LOCALE_STORAGE_KEY ? storedLocale : null,
},
navigator: { languages: [], language: "en" },
document: {
documentElement,
querySelector: (selector: string) => {
if (selector === '[data-i18n-meta="description"]') return meta;
if (selector === "[data-boot-copy]") return boot;
return null;
},
},
async function runPrebootLocale(storedLocale: string) {
const preboot = new Window({
url: "http://preboot.test",
settings: { disableJavaScriptFileLoading: true, disableCSSFileLoading: true },
});
return {
lang: documentElement.lang,
boot: boot.textContent,
description: meta.content,
};
try {
preboot.localStorage.setItem(LOCALE_STORAGE_KEY, storedLocale);
// Parse the shipped document and execute inline scripts in parser order.
// External/module loading stays disabled: React must not repair the splash.
preboot.document.write(INDEX_HTML);
return {
lang: preboot.document.documentElement.lang,
boot: preboot.document.querySelector('[role="status"]')?.textContent.trim(),
description: preboot.document.querySelector('meta[name="description"]')?.getAttribute("content"),
};
} finally {
await preboot.happyDOM.close();
}
}
function isRecord(value: unknown): value is Record<string, unknown> {
@@ -406,13 +387,6 @@ function interpolationKeys(value: unknown): string[] {
}
describe("webui i18n", () => {
it("runs preboot localization after the splash copy exists", () => {
expect(INDEX_HTML.indexOf(BOOT_COPY_MARKUP)).toBeGreaterThan(-1);
expect(INDEX_HTML.indexOf(PREBOOT_SCRIPT ?? "")).toBeGreaterThan(
INDEX_HTML.indexOf(BOOT_COPY_MARKUP),
);
});
it.each(supportedLocales)("localizes compaction states in $code", async ({ code }) => {
await setAppLanguage(code);
const copy = resources[code].common.thread.compaction;
@@ -437,9 +411,9 @@ describe("webui i18n", () => {
}
});
it("keeps preboot copy aligned with every registered locale", () => {
it("localizes the parsed splash in document order for every registered locale", async () => {
for (const { code } of supportedLocales) {
const result = runPrebootLocale(code);
const result = await runPrebootLocale(code);
const expected = resources[code].common.app;
expect({ code, ...result }).toEqual({
@@ -451,11 +425,11 @@ describe("webui i18n", () => {
}
});
it("normalizes Portuguese locales before the app bundle loads", () => {
it("normalizes Portuguese locales before the app bundle loads", async () => {
const expected = resources["pt-BR"].common.app;
for (const locale of ["pt", "pt-PT"]) {
expect(runPrebootLocale(locale)).toEqual({
expect(await runPrebootLocale(locale)).toEqual({
lang: "pt-BR",
boot: expected.loading.boot,
description: expected.meta.description,
+3 -1
View File
@@ -97,7 +97,9 @@ describe("file quick look", () => {
const quickLook = screen.getByTestId("file-image-quick-look");
expect(quickLook.textContent).toBe("");
expect(quickLook).toHaveClass("w-max");
expect(quickLook).not.toHaveClass("h-36", "w-full");
for (const className of ["h-36", "w-full"]) {
expect(quickLook).not.toHaveClass(className);
}
expect(quickLook.querySelector("img")).toHaveClass("rounded-mark", "object-contain");
expect(quickLook.querySelector("img")).toHaveClass("h-auto", "w-auto", "max-h-36");
expect(screen.getByRole("tooltip")).toHaveTextContent("File preview");
+3 -1
View File
@@ -12,7 +12,9 @@ describe("Linear workspace logo", () => {
expect(image).toHaveAttribute("height", "28");
expect(image).toHaveAttribute("referrerpolicy", "no-referrer");
expect(image.parentElement).toHaveClass("h-7", "w-7");
expect(image.parentElement).not.toHaveClass("overflow-hidden", "bg-muted");
for (const className of ["overflow-hidden", "bg-muted"]) {
expect(image.parentElement).not.toHaveClass(className);
}
expect(image).toHaveClass("object-contain");
expect(view.container.querySelector("svg")).toBeNull();
fireEvent.error(image);
@@ -1,3 +1,4 @@
import { waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const render = vi.fn();
@@ -12,28 +13,28 @@ vi.mock("@/App", () => ({
}));
describe("service worker registration when unsupported", () => {
const register = vi.fn(() => Promise.resolve());
beforeEach(() => {
vi.resetModules();
createRoot.mockClear();
render.mockClear();
register.mockClear();
document.body.innerHTML = '<div id="root"></div>';
// happy-dom's Navigator has no serviceWorker member, so this file runs
// without defining one — the entry's `"serviceWorker" in navigator` guard
// must keep registration from being attempted.
Reflect.deleteProperty(navigator, "serviceWorker");
});
afterEach(() => {
document.body.innerHTML = "";
delete (navigator as Navigator & { serviceWorker?: unknown }).serviceWorker;
Reflect.deleteProperty(navigator, "serviceWorker");
});
it("does not attempt registration when the service worker API is missing", async () => {
it("renders the app when the service worker API is missing", async () => {
expect("serviceWorker" in navigator).toBe(false);
await import("../main");
window.dispatchEvent(new Event("load"));
expect(register).not.toHaveBeenCalled();
await waitFor(() => {
expect(createRoot).toHaveBeenCalledWith(document.getElementById("root"));
expect(render).toHaveBeenCalledTimes(1);
});
});
});
-26
View File
@@ -142,30 +142,4 @@ describe("MarkdownText", () => {
"true",
);
});
it("defers syntax highlighting until the final render", async () => {
rendererSpy.mockClear();
const largeCode = `\`\`\`ts\n${"const value = 1;\n".repeat(1_100)}\`\`\``;
const { rerender } = render(
<MarkdownText streaming>{largeCode}</MarkdownText>,
);
await act(async () => {
await Promise.resolve();
await Promise.resolve();
});
expect(screen.getByTestId("markdown-renderer")).toHaveAttribute(
"data-highlight-code",
"false",
);
rerender(<MarkdownText>{largeCode}</MarkdownText>);
expect(screen.getByTestId("markdown-renderer")).toHaveAttribute(
"data-highlight-code",
"true",
);
});
});
+10 -4
View File
@@ -274,31 +274,37 @@ describe("MessageBubble", () => {
expect(bubble).toHaveClass("bg-secondary/70");
});
it("does not replay an entrance animation when persisted messages mount", () => {
it("renders completed message branches with static wrapper classes", async () => {
const messages: UIMessage[] = [
{
id: "u-persisted",
role: "user",
content: "Earlier question",
createdAt: Date.now(),
createdAt: 1_700_000_000_000,
},
{
id: "a-persisted",
role: "assistant",
content: "Earlier answer",
createdAt: Date.now(),
createdAt: 1_700_000_001_000,
},
{
id: "t-persisted",
role: "tool",
kind: "trace",
content: "Earlier tool call",
createdAt: Date.now(),
createdAt: 1_700_000_002_000,
},
];
for (const message of messages) {
const { container, unmount } = render(<MessageBubble message={message} />);
if (message.kind === "trace") {
const disclosure = screen.getByRole("button", { expanded: false });
fireEvent.click(disclosure);
expect(disclosure).toHaveAttribute("aria-expanded", "true");
}
expect(await screen.findByText(message.content)).toBeVisible();
for (const className of ["animate-in", "fade-in-0", "slide-in-from-bottom-1"]) {
expect(container.firstElementChild).not.toHaveClass(className);
}
+6 -2
View File
@@ -40,7 +40,9 @@ describe("settings provider icons", () => {
expect(icon).not.toHaveAttribute("style");
expect(fallback).toHaveClass("opacity-0");
expect(image).toHaveClass("opacity-100");
expect(image).not.toHaveClass("invert", "grayscale");
for (const className of ["invert", "grayscale"]) {
expect(image).not.toHaveClass(className);
}
},
);
@@ -60,7 +62,9 @@ describe("settings provider icons", () => {
fireEvent.load(image);
expect(image).toHaveClass("opacity-100");
expect(icon).toHaveClass("bg-transparent");
expect(icon).not.toHaveClass("bg-white", "bg-muted");
for (const className of ["bg-white", "bg-muted"]) {
expect(icon).not.toHaveClass(className);
}
fireEvent.error(image);
expect(image).toHaveAttribute("src", providerBrand(provider)!.logoUrls[1]);
@@ -2,6 +2,8 @@ import { fireEvent, render, screen, waitFor, within } from "@testing-library/rea
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import { RuntimeSettings } from "@/components/settings/system/RuntimeSettings";
import { RUNTIME_CONFIG_FIELDS, RUNTIME_CONFIG_GROUPS } from "@/components/settings/system/runtime-config-fields";
import runtimeConfigKeys from "../../../tests/webui/fixtures/runtime-config-keys.json";
import { TimezonePicker } from "@/components/settings/shared/TimezonePicker";
import { DEFAULT_AGENT_SETTINGS_DRAFT } from "@/components/settings/models/ModelsSettings";
import { installSettingsViewTestHooks, jsonResponse, renderSettingsView, requestMutationMock, settingsPayload } from "@/tests/settings-test-utils";
@@ -29,6 +31,15 @@ function runtimeSettings() {
describe("Runtime configuration settings", () => {
installSettingsViewTestHooks();
it("covers the shared runtime wire-key catalogue without duplicate editors", () => {
const paths = RUNTIME_CONFIG_FIELDS.map((field) => field.path);
expect(new Set(paths).size).toBe(paths.length);
// This key gates the CLI group rather than having a separate editor.
const visibilityOnly = "tools.cli_apps.enable";
expect(RUNTIME_CONFIG_GROUPS.find((group) => group.id === "cli")?.enabledBy).toBe(visibilityOnly);
expect([...paths, visibilityOnly].sort()).toEqual([...runtimeConfigKeys].sort());
});
it("keeps local service controls available when tool families are disabled", () => {
const payload = runtimeSettings();
renderSettingsView({ initialSection: "advanced", initialSettings: {
+6 -2
View File
@@ -203,7 +203,9 @@ describe("Settings system domains", () => {
expect(title.parentElement).toHaveClass("settings-section-heading");
expect(title.nextElementSibling).toHaveTextContent("1");
expect(title.nextElementSibling).toHaveClass("tabular-nums");
expect(title.nextElementSibling).not.toHaveClass("rounded-full", "bg-muted");
for (const className of ["rounded-full", "bg-muted"]) {
expect(title.nextElementSibling).not.toHaveClass(className);
}
fireEvent.click(screen.getByRole("button", { name: "MCP", exact: true }));
const mcpTitle = screen.getByRole("heading", { name: "MCP tools" });
@@ -267,7 +269,9 @@ describe("Settings system domains", () => {
for (const name of ["Custom", "Built-in", "Other"]) {
const title = screen.getByRole("heading", { name, exact: true });
expect(title).toHaveClass("text-[13px]", "font-medium", "leading-5");
expect(title).not.toHaveClass("uppercase", "tracking-[0.08em]");
for (const className of ["uppercase", "tracking-[0.08em]"]) {
expect(title).not.toHaveClass(className);
}
expect(title.nextElementSibling).toHaveTextContent("1");
expect(title.nextElementSibling).toHaveClass("leading-5");
}
+10 -12
View File
@@ -139,10 +139,10 @@ function indexHtml(assetPaths: string[]): Response {
return new Response(`<!doctype html><html><head>${refs}</head></html>`);
}
function fetchEvent(url: string) {
function fetchEvent(url: string, init?: RequestInit) {
const respondWith = vi.fn();
const event = {
request: new Request(url, { method: "GET" }),
request: new Request(url, init),
respondWith,
};
return { event, respondWith };
@@ -223,8 +223,8 @@ describe("service worker", () => {
];
for (const path of paths) {
const { respondWith } = fetchEvent(`${ORIGIN}${path}`);
await sw.fire("fetch", { request: new Request(`${ORIGIN}${path}`) });
const { event, respondWith } = fetchEvent(`${ORIGIN}${path}`);
await sw.fire("fetch", event);
expect(respondWith, path).not.toHaveBeenCalled();
}
expect(sw.fetchMock).not.toHaveBeenCalled();
@@ -233,16 +233,14 @@ describe("service worker", () => {
it("does not intercept non-GET or unrelated cross-origin requests", async () => {
const sw = loadSw();
const { respondWith: post } = fetchEvent(`${ORIGIN}/api/v1/models`);
await sw.fire("fetch", {
request: new Request(`${ORIGIN}/api/v1/models`, { method: "POST" }),
});
const { event: postEvent, respondWith: post } = fetchEvent(
`${ORIGIN}/assets/app.js`, { method: "POST" },
);
await sw.fire("fetch", postEvent);
expect(post).not.toHaveBeenCalled();
const { respondWith: cross } = fetchEvent("https://other.test/assets/app.js");
await sw.fire("fetch", {
request: new Request("https://other.test/assets/app.js"),
});
const { event: crossEvent, respondWith: cross } = fetchEvent("https://other.test/assets/app.js");
await sw.fire("fetch", crossEvent);
expect(cross).not.toHaveBeenCalled();
expect(sw.fetchMock).not.toHaveBeenCalled();
});
+3 -1
View File
@@ -816,7 +816,9 @@ describe("ThreadComposer", () => {
expect(modelPill).not.toHaveClass("font-semibold");
const providerLogo = screen.getByTestId("composer-model-logo-openai");
expect(providerLogo).toBeInTheDocument();
expect(providerLogo).not.toHaveClass("border", "bg-background");
for (const className of ["border", "bg-background"]) {
expect(providerLogo).not.toHaveClass(className);
}
const input = screen.getByPlaceholderText("Type your message...");
expect(input.className).toContain("min-h-[50px]");
expect(input.className).toContain("text-[16px]");
+6 -2
View File
@@ -731,7 +731,9 @@ describe("ThreadMessages", () => {
const rows = Array.from(container.firstElementChild?.children ?? []);
expect(rows).toHaveLength(2);
expect(rows[0]).not.toHaveClass("mt-2", "mt-4", "mt-5");
for (const className of ["mt-2", "mt-4", "mt-5"]) {
expect(rows[0]).not.toHaveClass(className);
}
expect(rows[1]).not.toHaveClass("mt-4");
const answerRow = screen.getByText("final answer")
.closest<HTMLElement>("[data-thread-display-unit]")!;
@@ -772,7 +774,9 @@ describe("ThreadMessages", () => {
expect(disclosure.compareDocumentPosition(timestamp) & Node.DOCUMENT_POSITION_FOLLOWING)
.toBeTruthy();
expect(menu).toHaveClass("w-max", "max-w-64", "bg-popover", "rounded-floating", "overflow-y-auto");
expect(menu).not.toHaveClass("min-w-[8.5rem]", "bg-popover/95", "rounded-xl");
for (const className of ["min-w-[8.5rem]", "bg-popover/95", "rounded-xl"]) {
expect(menu).not.toHaveClass(className);
}
const menuButtons = Array.from(menu.querySelectorAll("button"));
expect(menuButtons.length).toBeGreaterThan(1);
for (const button of menuButtons) {
+2 -2
View File
@@ -24,7 +24,7 @@ import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
describe("UI shape system", () => {
it.each(["center", "bottom"] as const)("keeps an oversized %s dialog scrollable from its start", (placement) => {
it.each(["center", "bottom"] as const)("declares a scroll owner inside the %s modal boundary", (placement) => {
render(<Dialog open><DialogContent placement={placement}>
<DialogTitle>Long dialog</DialogTitle>
<DialogDescription>Content that can outgrow a keyboard-fitted frame.</DialogDescription>
@@ -32,7 +32,7 @@ describe("UI shape system", () => {
const dialog = screen.getByRole("dialog");
expect(dialog.parentElement).toHaveClass("items-start", "overflow-y-auto");
// The scroll owner stays inside Radix's overlay/scroll-lock boundary.
expect(dialog.parentElement?.parentElement).toHaveClass("backdrop-blur-[8px]", "duration-200");
expect(dialog.parentElement?.parentElement).toHaveAttribute("data-state", "open");
expect(dialog).toHaveClass(placement === "bottom" ? "mt-auto" : "my-auto");
});
+27 -14
View File
@@ -1,14 +1,14 @@
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { gunzipSync } from "node:zlib";
import { describe, expect, it } from "vitest";
import { rollup } from "rollup";
import webuiConfig, {
entryLazyFeatureImports,
gzipWebuiAssets,
webuiManualChunk,
writeCompressedWebuiAssets,
} from "../../vite.config";
describe("development overlay dependencies", () => {
@@ -20,24 +20,37 @@ describe("development overlay dependencies", () => {
});
describe("gzipWebuiAssets", () => {
it("compresses finalized files after Rollup writes the bundle", () => {
it("compresses finalized files after Rollup writes the bundle", async () => {
const plugin = gzipWebuiAssets();
expect(plugin.generateBundle).toBeUndefined();
expect(plugin.writeBundle).toBeTypeOf("function");
const outputDir = mkdtempSync(path.join(tmpdir(), "nanobot-vite-gzip-"));
const assetPath = path.join(outputDir, "assets", "index-final.js");
const finalized = Buffer.from(
"const __vite__mapDeps = ['assets/lazy-feature.js'];\n".repeat(200),
);
const build = await rollup({
input: "virtual-entry",
plugins: [
{
name: "fixture-entry",
resolveId: (id) => id === "virtual-entry" ? id : null,
load: (id) => id === "virtual-entry" ? 'console.log("stale in-memory bytes");' : null,
},
{
name: "finalize-on-disk",
writeBundle: {
sequential: true,
handler() { writeFileSync(assetPath, finalized); },
},
},
plugin,
],
});
try {
const assetPath = path.join(outputDir, "assets", "index-final.js");
mkdirSync(path.dirname(assetPath), { recursive: true });
const finalized = Buffer.from(
"const __vite__mapDeps = ['assets/lazy-feature.js'];\n".repeat(200),
);
writeFileSync(assetPath, finalized);
writeCompressedWebuiAssets(outputDir, ["assets/index-final.js"]);
await build.write({ dir: outputDir, format: "es", entryFileNames: "assets/index-final.js" });
expect(gunzipSync(readFileSync(`${assetPath}.gz`))).toEqual(finalized);
} finally {
await build.close();
rmSync(outputDir, { recursive: true, force: true });
}
});
+2 -1
View File
@@ -7,7 +7,8 @@ function payload(id: string): WebuiThreadPersistedPayload {
return {
schemaVersion: 3,
revision: `rev-${id}`,
messages: [{ id, role: "assistant", content: id, createdAt: 1 }],
projection: "events",
events: [{ event: "message", chat_id: id, text: id }],
};
}