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
95 changes: 95 additions & 0 deletions client-web/lib/queries/privateMessages.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { act, renderHook, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { createTestQueryClient, queryClientWrapper } from "../../test/reactQuery";
import { apiFetch } from "../api";
import { usePrivateMessages, useSendPrivateMessage } from "./privateMessages";

vi.mock("../api", () => ({
apiFetch: vi.fn(),
}));

const mockedApiFetch = vi.mocked(apiFetch);

function jsonResponse(body: unknown, status = 200) {
return new Response(JSON.stringify(body), {
status,
headers: { "Content-Type": "application/json" },
});
}

afterEach(() => {
vi.clearAllMocks();
});

describe("private message mutations", () => {
it("loads a peer conversation newest-first from the backend", async () => {
const queryClient = createTestQueryClient();
const messages = [
{
id: "pm-new",
sender_id: "peer-1",
recipient_id: "me",
content: "newest",
created_at: "2026-06-26T00:00:01Z",
},
{
id: "pm-old",
sender_id: "me",
recipient_id: "peer-1",
content: "oldest",
created_at: "2026-06-26T00:00:00Z",
},
];
mockedApiFetch.mockResolvedValueOnce(jsonResponse({ messages }));

const { result } = renderHook(() => usePrivateMessages("peer-1"), {
wrapper: queryClientWrapper(queryClient),
});

await waitFor(() => expect(result.current.isSuccess).toBe(true));

expect(mockedApiFetch).toHaveBeenCalledWith("/api/private-messages?peer_id=peer-1");
expect(result.current.data).toEqual(messages);
});

it("invalidates exactly the recipient conversation after sending", async () => {
const queryClient = createTestQueryClient();
const invalidate = vi.spyOn(queryClient, "invalidateQueries");
mockedApiFetch.mockResolvedValueOnce(
jsonResponse({
id: "pm-1",
sender_id: "me",
recipient_id: "peer-1",
content: "hello",
created_at: "2026-06-26T00:00:00Z",
}),
);

const { result } = renderHook(() => useSendPrivateMessage(), {
wrapper: queryClientWrapper(queryClient),
});

await act(async () => {
await result.current.mutateAsync({ recipientId: "peer-1", content: "hello" });
});

expect(mockedApiFetch).toHaveBeenCalledWith("/api/private-messages", {
method: "POST",
body: JSON.stringify({ recipient_id: "peer-1", content: "hello" }),
});
expect(invalidate).toHaveBeenCalledWith({ queryKey: ["private-messages", "peer-1"] });
});

it("surfaces backend error codes when send fails", async () => {
const queryClient = createTestQueryClient();
mockedApiFetch.mockResolvedValueOnce(jsonResponse({ code: "no_shared_team" }, 403));

const { result } = renderHook(() => useSendPrivateMessage(), {
wrapper: queryClientWrapper(queryClient),
});

await expect(
result.current.mutateAsync({ recipientId: "peer-2", content: "hello" }),
).rejects.toThrow("no_shared_team");
});
});
182 changes: 182 additions & 0 deletions client-web/lib/queries/releases.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
import { act, renderHook, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { createTestQueryClient, queryClientWrapper } from "../../test/reactQuery";
import { apiFetch } from "../api";
import type { Release } from "./releases";
import {
useCancelRelease,
useCreateRelease,
useLinkIncident,
useRelease,
useReleases,
useUnlinkIncident,
useValidateStep,
} from "./releases";

vi.mock("../api", () => ({
apiFetch: vi.fn(),
}));

const mockedApiFetch = vi.mocked(apiFetch);

function jsonResponse(body: unknown, status = 200) {
return new Response(JSON.stringify(body), {
status,
headers: { "Content-Type": "application/json" },
});
}

function release(overrides: Partial<Release> = {}): Release {
return {
release_id: "release-1",
team_id: "team-1",
title: "Deploy demo",
state: "created",
steps: [{ name: "build", validated: false, validated_by: null, validated_at: null }],
linked_incident_ids: [],
created_at: "2026-06-26T00:00:00Z",
...overrides,
};
}

async function expectMutationInvalidates<TVariables>(
useHook: () => { mutateAsync: (variables: TVariables) => Promise<unknown> },
variables: TVariables,
url: string,
method: string,
) {
const queryClient = createTestQueryClient();
const invalidate = vi.spyOn(queryClient, "invalidateQueries");
mockedApiFetch.mockResolvedValueOnce(jsonResponse(release({ release_id: "release-1" })));

const { result } = renderHook(() => useHook(), {
wrapper: queryClientWrapper(queryClient),
});

await act(async () => {
await result.current.mutateAsync(variables);
});

expect(mockedApiFetch).toHaveBeenCalledWith(url, { method });
expect(invalidate).toHaveBeenCalledWith({ queryKey: ["releases", { teamId: "team-1" }] });
expect(invalidate).toHaveBeenCalledWith({ queryKey: ["release", "release-1"] });
}

afterEach(() => {
vi.clearAllMocks();
});

describe("release query mutations", () => {
it("loads the team's releases", async () => {
const queryClient = createTestQueryClient();
const releases = [release({ release_id: "release-a" })];
mockedApiFetch.mockResolvedValueOnce(jsonResponse(releases));

const { result } = renderHook(() => useReleases("team-1"), {
wrapper: queryClientWrapper(queryClient),
});

await waitFor(() => expect(result.current.isSuccess).toBe(true));

expect(mockedApiFetch).toHaveBeenCalledWith("/api/releases?team_id=team-1");
expect(result.current.data).toEqual(releases);
});

it("loads a single release detail", async () => {
const queryClient = createTestQueryClient();
const detail = release({ release_id: "release-detail" });
mockedApiFetch.mockResolvedValueOnce(jsonResponse(detail));

const { result } = renderHook(() => useRelease("release-detail"), {
wrapper: queryClientWrapper(queryClient),
});

await waitFor(() => expect(result.current.isSuccess).toBe(true));

expect(mockedApiFetch).toHaveBeenCalledWith("/api/releases/release-detail");
expect(result.current.data).toEqual(detail);
});

it("adds a created release to list and detail caches immediately", async () => {
const queryClient = createTestQueryClient();
const existing = release({ release_id: "release-old", title: "Previous deploy" });
const created = release({ release_id: "release-new", title: "New deploy" });
queryClient.setQueryData(["releases", { teamId: "team-1" }], [existing]);
mockedApiFetch.mockResolvedValueOnce(jsonResponse(created, 201));

const { result } = renderHook(() => useCreateRelease(), {
wrapper: queryClientWrapper(queryClient),
});

await act(async () => {
await result.current.mutateAsync({
team_id: "team-1",
title: "New deploy",
steps: ["build"],
});
});

expect(mockedApiFetch).toHaveBeenCalledWith("/api/releases", {
method: "POST",
body: JSON.stringify({ team_id: "team-1", title: "New deploy", steps: ["build"] }),
});
expect(queryClient.getQueryData<Release[]>(["releases", { teamId: "team-1" }])).toEqual([
created,
existing,
]);
expect(queryClient.getQueryData<Release>(["release", "release-new"])).toEqual(created);
});

it("surfaces backend error codes on release actions", async () => {
const queryClient = createTestQueryClient();
mockedApiFetch.mockResolvedValueOnce(jsonResponse({ code: "release_blocked" }, 409));

const { result } = renderHook(() => useValidateStep(), {
wrapper: queryClientWrapper(queryClient),
});

await expect(
result.current.mutateAsync({
releaseId: "release-1",
step: "production",
teamId: "team-1",
}),
).rejects.toThrow("release_blocked");
});

it("invalidates list and detail caches after validating a step", async () => {
await expectMutationInvalidates(
() => useValidateStep(),
{ releaseId: "release-1", step: "build", teamId: "team-1" },
"/api/releases/release-1/steps/build/validate",
"POST",
);
});

it("invalidates list and detail caches after linking an incident", async () => {
await expectMutationInvalidates(
() => useLinkIncident(),
{ releaseId: "release-1", incidentId: "incident-1", teamId: "team-1" },
"/api/releases/release-1/incidents/incident-1/link",
"POST",
);
});

it("invalidates list and detail caches after unlinking an incident", async () => {
await expectMutationInvalidates(
() => useUnlinkIncident(),
{ releaseId: "release-1", incidentId: "incident-1", teamId: "team-1" },
"/api/releases/release-1/incidents/incident-1/link",
"DELETE",
);
});

it("invalidates list and detail caches after cancelling a release", async () => {
await expectMutationInvalidates(
() => useCancelRelease(),
{ releaseId: "release-1", teamId: "team-1" },
"/api/releases/release-1/cancel",
"POST",
);
});
});
12 changes: 10 additions & 2 deletions client-web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@
"lint": "eslint .",
"format": "prettier --write .",
"format:check": "prettier --check .",
"typecheck": "tsc --noEmit"
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:coverage": "vitest run --coverage"
},
"dependencies": {
"@tanstack/react-query": "^5.101.0",
Expand All @@ -27,15 +29,21 @@
},
"devDependencies": {
"@tailwindcss/postcss": "^4.3.0",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
"@types/node": "^24",
"@types/react": "19.2.17",
"@types/react-dom": "19.2.3",
"@vitejs/plugin-react": "^6.0.3",
"@vitest/coverage-v8": "^4.1.9",
"eslint": "9.39.4",
"eslint-config-next": "16.2.7",
"jsdom": "^29.1.1",
"postcss": "^8.5.15",
"prettier": "3.8.3",
"prettier-plugin-tailwindcss": "^0.8.0",
"tailwindcss": "^4.3.0",
"typescript": "6.0.3"
"typescript": "6.0.3",
"vitest": "^4.1.9"
}
}
17 changes: 17 additions & 0 deletions client-web/test/reactQuery.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { ReactNode } from "react";

export function createTestQueryClient() {
return new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
});
}

export function queryClientWrapper(queryClient: QueryClient) {
return function QueryClientWrapper({ children }: { children: ReactNode }) {
return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;
};
}
23 changes: 23 additions & 0 deletions client-web/vitest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import react from "@vitejs/plugin-react";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { defineConfig } from "vitest/config";

const root = path.dirname(fileURLToPath(import.meta.url));

export default defineConfig({
plugins: [react()],
resolve: {
alias: {
"@": root,
},
},
test: {
environment: "jsdom",
setupFiles: ["./vitest.setup.ts"],
coverage: {
include: ["lib/queries/privateMessages.ts", "lib/queries/releases.ts"],
reporter: ["text"],
},
},
});
1 change: 1 addition & 0 deletions client-web/vitest.setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import "@testing-library/jest-dom/vitest";
Loading