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
23 changes: 23 additions & 0 deletions client/src/app/features/user/apis/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,29 @@ describe("createUserApi", () => {
});
});

describe("deleteUser", () => {
it("sends a DELETE request to the users endpoint", async () => {
fetchSpy.mockResolvedValue({ ok: true, status: 204, json: async () => ({}) } as Response);

await api.deleteUser(1);

expect(fetchSpy).toHaveBeenCalledWith(
`${USERS_ENDPOINT}/1`,
expect.objectContaining({
method: "DELETE",
headers: expect.objectContaining({ Accept: "application/json" }),
credentials: "omit",
}),
);
});

it("throws on HTTP error", async () => {
fetchSpy.mockResolvedValue(makeNgResponse(404) as Response);

await expect(api.deleteUser(1)).rejects.toThrow("HTTP 404");
});
});

it("throws when apiBase is empty", () => {
expect(() => createUserApi({ apiBase: "", fetchImpl: fetchSpy })).toThrow(
"apiBase is required",
Expand Down
1 change: 1 addition & 0 deletions client/src/app/features/user/apis/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ const userApi = createUserApi({ apiBase });
export const createUser = userApi.createUser;
export const getUser = userApi.getUser;
export const updateUser = userApi.updateUser;
export const deleteUser = userApi.deleteUser;
19 changes: 19 additions & 0 deletions client/src/app/features/user/apis/user-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,17 @@ export const createUserApi = ({ apiBase, fetchImpl = fetch }: UserApiDeps) => {
signal: init?.signal,
});

const withDeleteInit = (init?: RequestInit): RequestInit => ({
...init,
method: "DELETE",
headers: {
Accept: "application/json",
...(init?.headers ?? {}),
},
credentials: init?.credentials ?? "omit",
signal: init?.signal,
});

return {
async createUser(request: CreateUserRequest, init?: RequestInit): Promise<ApiUserDto> {
const response = await fetchImpl(createEndpoint, {
Expand Down Expand Up @@ -141,5 +152,13 @@ export const createUserApi = ({ apiBase, fetchImpl = fetch }: UserApiDeps) => {

return json.data;
},

async deleteUser(id: number, init?: RequestInit): Promise<void> {
const response = await fetchImpl(`${usersEndpoint}/${id}`, withDeleteInit(init));

if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
},
};
};
64 changes: 63 additions & 1 deletion client/src/app/features/user/components/UserProfileView.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { useEffect, useRef, useState } from "react";
import type { FormEvent } from "react";
import Dialog from "@mui/material/Dialog";
import DialogTitle from "@mui/material/DialogTitle";
import DialogContent from "@mui/material/DialogContent";
import DialogActions from "@mui/material/DialogActions";
import TextField from "@shared/uis/TextField.tsx";
import { Button } from "@shared/uis/Button.tsx";
import { ErrorPanel } from "@shared/uis/ErrorPanel.tsx";
Expand All @@ -12,6 +16,9 @@ type Props = {
onUpdate: (values: UpdateUserFormValues) => void;
isUpdating: boolean;
updateError: unknown;
onDelete: () => void;
isDeleting: boolean;
deleteError: unknown;
};

type EditableField = keyof UpdateUserFormValues;
Expand All @@ -25,11 +32,21 @@ const toFormValues = (profile: UserProfile): UpdateUserFormValues => ({
email: profile.email,
});

export function UserProfileView({ profile, onUpdate, isUpdating, updateError }: Props) {
export function UserProfileView({
profile,
onUpdate,
isUpdating,
updateError,
onDelete,
isDeleting,
deleteError,
}: Props) {
const text = useText();
const [editingField, setEditingField] = useState<EditableField | null>(null);
const [fieldValue, setFieldValue] = useState("");
const [isConfirmingDelete, setIsConfirmingDelete] = useState(false);
const wasUpdatingRef = useRef(false);
const wasDeletingRef = useRef(false);

useEffect(() => {
if (wasUpdatingRef.current && !isUpdating && updateError == null) {
Expand All @@ -38,6 +55,13 @@ export function UserProfileView({ profile, onUpdate, isUpdating, updateError }:
wasUpdatingRef.current = isUpdating;
}, [isUpdating, updateError]);

useEffect(() => {
if (wasDeletingRef.current && !isDeleting && deleteError != null) {
setIsConfirmingDelete(false);
}
wasDeletingRef.current = isDeleting;
}, [isDeleting, deleteError]);

const startEditing = (field: EditableField) => {
setFieldValue(profile[field]);
setEditingField(field);
Expand All @@ -53,6 +77,10 @@ export function UserProfileView({ profile, onUpdate, isUpdating, updateError }:
onUpdate({ ...toFormValues(profile), [editingField]: fieldValue });
};

const handleConfirmDelete = () => {
onDelete();
};

return (
<div className="mx-auto flex max-w-xl flex-col items-center gap-6 px-4 py-12">
<div className="flex h-24 w-24 items-center justify-center rounded-full bg-indigo-600 text-3xl font-semibold text-white">
Expand Down Expand Up @@ -118,6 +146,40 @@ export function UserProfileView({ profile, onUpdate, isUpdating, updateError }:
<ProfileRow label={text.userAgeRange} value={profile.ageRange} />
<ProfileRow label={text.userSubscriptionTier} value={profile.subscriptionTier} />
</div>

{deleteError != null && <ErrorPanel message={text.userDeleteError} />}

<Button
type="button"
variant="destructive"
onClick={() => setIsConfirmingDelete(true)}
disabled={isDeleting}
>
{text.userDeleteButton}
</Button>

<Dialog open={isConfirmingDelete} onClose={() => setIsConfirmingDelete(false)}>
<DialogTitle>{text.userDeleteConfirmTitle}</DialogTitle>
<DialogContent>{text.userDeleteConfirmMessage}</DialogContent>
<DialogActions>
<Button
type="button"
variant="secondary"
onClick={() => setIsConfirmingDelete(false)}
disabled={isDeleting}
>
{text.userUpdateCancel}
</Button>
<Button
type="button"
variant="destructive"
onClick={handleConfirmDelete}
isLoading={isDeleting}
>
{text.userDeleteButton}
</Button>
</DialogActions>
</Dialog>
</div>
);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/** @jest-environment jsdom */

import { render, screen, fireEvent } from "@testing-library/react";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { LocaleProvider } from "@shared/locale/LocaleProvider.tsx";
import { UserProfileView } from "../UserProfileView";
Expand All @@ -22,6 +22,9 @@ const renderView = (props: Partial<React.ComponentProps<typeof UserProfileView>>
onUpdate: jest.fn(),
isUpdating: false,
updateError: null,
onDelete: jest.fn(),
isDeleting: false,
deleteError: null,
...props,
};

Expand Down Expand Up @@ -125,7 +128,14 @@ describe("UserProfileView", () => {
rerender(
<MemoryRouter>
<LocaleProvider>
<UserProfileView profile={profile} onUpdate={jest.fn()} {...props} />
<UserProfileView
profile={profile}
onUpdate={jest.fn()}
onDelete={jest.fn()}
isDeleting={false}
deleteError={null}
{...props}
/>
</LocaleProvider>
</MemoryRouter>,
);
Expand All @@ -150,4 +160,45 @@ describe("UserProfileView", () => {
expect(screen.queryByLabelText(/^First Name/)).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "Edit First Name" })).toBeInTheDocument();
});

it("opens a confirmation dialog when Delete User is clicked", () => {
renderView();

fireEvent.click(screen.getByRole("button", { name: "Delete User" }));

expect(
screen.getByText("Are you sure you want to delete this user?", { exact: false }),
).toBeInTheDocument();
});

it("closes the dialog without calling onDelete when Cancel is clicked", async () => {
const onDelete = jest.fn();
renderView({ onDelete });

fireEvent.click(screen.getByRole("button", { name: "Delete User" }));
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));

expect(onDelete).not.toHaveBeenCalled();
await waitFor(() => {
expect(
screen.queryByText("Are you sure you want to delete this user?", { exact: false }),
).not.toBeInTheDocument();
});
});

it("calls onDelete when the dialog's Delete User button is confirmed", () => {
const onDelete = jest.fn();
renderView({ onDelete });

fireEvent.click(screen.getByRole("button", { name: "Delete User" }));
fireEvent.click(screen.getByRole("button", { name: "Delete User" }));

expect(onDelete).toHaveBeenCalledTimes(1);
});

it("shows an error panel when deleteError is present", () => {
renderView({ deleteError: new Error("boom") });

expect(screen.getByText("Failed to delete user.")).toBeInTheDocument();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { UserProfile } from "../../types";

const useGetUserMock = jest.fn();
const useUpdateUserMock = jest.fn();
const useDeleteUserMock = jest.fn();

jest.mock("../../hooks/use-get-user", () => ({
useGetUser: (id: number) => useGetUserMock(id),
Expand All @@ -13,6 +14,10 @@ jest.mock("../../hooks/use-update-user", () => ({
useUpdateUser: () => useUpdateUserMock(),
}));

jest.mock("../../hooks/use-delete-user", () => ({
useDeleteUser: () => useDeleteUserMock(),
}));

import { render, screen, fireEvent } from "@testing-library/react";
import { MemoryRouter, Routes, Route } from "react-router-dom";
import { LocaleProvider } from "@shared/locale/LocaleProvider.tsx";
Expand All @@ -34,22 +39,30 @@ const renderContainer = (id = "1") =>
<LocaleProvider>
<Routes>
<Route path="/users/:id" element={<UserGetContainer />} />
<Route path="/heritages" element={<div>Heritages Home</div>} />
</Routes>
</LocaleProvider>
</MemoryRouter>,
);

describe("UserGetContainer", () => {
const submitMock = jest.fn();
const submitUpdateMock = jest.fn();
const submitDeleteMock = jest.fn();

beforeEach(() => {
jest.clearAllMocks();
useUpdateUserMock.mockReturnValue({
submit: submitMock,
submit: submitUpdateMock,
data: null,
isLoading: false,
error: null,
});
useDeleteUserMock.mockReturnValue({
submit: submitDeleteMock,
done: false,
isLoading: false,
error: null,
});
});

it("shows a spinner while loading", () => {
Expand Down Expand Up @@ -102,7 +115,7 @@ describe("UserGetContainer", () => {
fireEvent.change(screen.getByLabelText(/^First Name/), { target: { value: "Jiro" } });
fireEvent.click(screen.getByRole("button", { name: "Save" }));

expect(submitMock).toHaveBeenCalledWith(
expect(submitUpdateMock).toHaveBeenCalledWith(
42,
expect.objectContaining({ firstName: "Jiro", lastName: "Yamada", email: "taro@example.com" }),
);
Expand All @@ -111,7 +124,7 @@ describe("UserGetContainer", () => {
it("reflects the updated profile immediately once useUpdateUser returns data", () => {
useGetUserMock.mockReturnValue({ data: profile, isLoading: false, error: null });
useUpdateUserMock.mockReturnValue({
submit: submitMock,
submit: submitUpdateMock,
data: { ...profile, firstName: "Jiro" },
isLoading: false,
error: null,
Expand All @@ -121,4 +134,29 @@ describe("UserGetContainer", () => {

expect(screen.getByText("Jiro Yamada")).toBeInTheDocument();
});

it("calls useDeleteUser's submit with the numeric id after confirming deletion", () => {
useGetUserMock.mockReturnValue({ data: profile, isLoading: false, error: null });

renderContainer("42");

fireEvent.click(screen.getByRole("button", { name: "Delete User" }));
fireEvent.click(screen.getByRole("button", { name: "Delete User" }));

expect(submitDeleteMock).toHaveBeenCalledWith(42);
});

it("navigates to /heritages once useDeleteUser reports done", () => {
useGetUserMock.mockReturnValue({ data: profile, isLoading: false, error: null });
useDeleteUserMock.mockReturnValue({
submit: submitDeleteMock,
done: true,
isLoading: false,
error: null,
});

renderContainer();

expect(screen.getByText("Heritages Home")).toBeInTheDocument();
});
});
Loading
Loading