@@ -19,7 +20,7 @@ export function PetList({ pets }: PetListProps) {
return (
{pets.map((pet) => (
-
+
))}
)
diff --git a/src/features/pets/hooks/delete-pet-handler/useDeletePetHandler.test.ts b/src/features/pets/hooks/delete-pet-handler/useDeletePetHandler.test.ts
new file mode 100644
index 0000000..4d95fdf
--- /dev/null
+++ b/src/features/pets/hooks/delete-pet-handler/useDeletePetHandler.test.ts
@@ -0,0 +1,97 @@
+import { renderHook, act } from "@testing-library/react"
+import { useDeletePetHandler } from "./useDeletePetHandler"
+import { useDeletePet } from "../delete-pet/useDeletePet"
+import { toast } from "sonner"
+import * as toastUtils from "@/shared/utils/toast-utils"
+import { mockNavigation } from "../../../../../jest.setup"
+import axios from "axios"
+import { QueryClientProviderMock } from "@/shared/test-utils/providers/query-client-provider.mock"
+import { petResponseMock } from "@/shared/test-utils/mocks/pets-mocks"
+
+jest.mock("../delete-pet/useDeletePet", () => ({
+ useDeletePet: jest.fn(),
+}))
+
+jest.mock("sonner", () => ({
+ toast: { success: jest.fn() },
+}))
+
+jest.mock("@/shared/utils/toast-utils", () => ({
+ showErrorToast: jest.fn(),
+}))
+
+jest.mock("axios", () => ({
+ isAxiosError: jest.fn(),
+}))
+
+const PET_ID = petResponseMock.id
+
+describe(useDeletePetHandler.name, () => {
+ const mutate = jest.fn()
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ ;(useDeletePet as jest.Mock).mockReturnValue({ mutate, isPending: false })
+ })
+
+ it("should handle success: show toast and navigate", () => {
+ ;(useDeletePet as jest.Mock).mockReturnValue({
+ mutate: (_id: string, options: { onSuccess: () => void }) =>
+ options.onSuccess(),
+ })
+
+ const { result } = renderHook(() => useDeletePetHandler(), {
+ wrapper: QueryClientProviderMock,
+ })
+ act(() => {
+ result.current.handleDeletePet(PET_ID)
+ })
+
+ expect(toast.success).toHaveBeenCalledWith("Pet excluído com sucesso!")
+ expect(mockNavigation.routerFunctions.push).toHaveBeenCalledWith("/pets")
+ })
+
+ it("should handle 404 error: show not found toast, and navigate", () => {
+ ;(axios.isAxiosError as unknown as jest.Mock).mockReturnValue(true)
+ ;(useDeletePet as jest.Mock).mockReturnValue({
+ mutate: (
+ _id: string,
+ options: { onError: (error: { status: number }) => void }
+ ) => options.onError({ status: 404 }),
+ })
+
+ const { result } = renderHook(() => useDeletePetHandler(), {
+ wrapper: QueryClientProviderMock,
+ })
+
+ act(() => {
+ result.current.handleDeletePet(PET_ID)
+ })
+
+ expect(toastUtils.showErrorToast).toHaveBeenCalledWith(
+ "O pet informado não foi encontrado."
+ )
+ expect(mockNavigation.routerFunctions.push).toHaveBeenCalledWith("/pets")
+ })
+
+ it("should handle generic error: show default error toast and navigate", () => {
+ ;(axios.isAxiosError as unknown as jest.Mock).mockReturnValue(false)
+ ;(useDeletePet as jest.Mock).mockReturnValue({
+ mutate: (
+ _id: string,
+ options: { onError: (error: { status: number }) => void }
+ ) => options.onError({ status: 500 }),
+ })
+
+ const { result } = renderHook(() => useDeletePetHandler(), {
+ wrapper: QueryClientProviderMock,
+ })
+
+ act(() => {
+ result.current.handleDeletePet(PET_ID)
+ })
+
+ expect(toastUtils.showErrorToast).toHaveBeenCalled()
+ expect(mockNavigation.routerFunctions.push).toHaveBeenCalledWith("/pets")
+ })
+})
diff --git a/src/features/pets/hooks/delete-pet-handler/useDeletePetHandler.ts b/src/features/pets/hooks/delete-pet-handler/useDeletePetHandler.ts
new file mode 100644
index 0000000..f8ba037
--- /dev/null
+++ b/src/features/pets/hooks/delete-pet-handler/useDeletePetHandler.ts
@@ -0,0 +1,45 @@
+import { useNavigate } from "@/shared/hooks/useNavigate"
+import { useQueryClient } from "@tanstack/react-query"
+import { useDeletePet } from "../delete-pet/useDeletePet"
+import { toast } from "sonner"
+import { showErrorToast } from "@/shared/utils/toast-utils"
+import axios from "axios"
+
+interface UseDeletePetHandlerResult {
+ handleDeletePet: (id: string) => void
+ isDeleting: boolean
+}
+
+export function useDeletePetHandler(): UseDeletePetHandlerResult {
+ const queryClient = useQueryClient()
+ const { toPets } = useNavigate()
+
+ const deletePetMutation = useDeletePet()
+
+ function handleDeletePet(id: string) {
+ deletePetMutation.mutate(
+ { id },
+ {
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ["pets"] })
+ toast.success("Pet excluído com sucesso!")
+ toPets()
+ },
+ onError: (error) => {
+ if (axios.isAxiosError(error) && error.status === 404) {
+ queryClient.invalidateQueries({ queryKey: ["pets"] })
+ showErrorToast("O pet informado não foi encontrado.")
+ } else {
+ showErrorToast()
+ }
+ toPets()
+ },
+ }
+ )
+ }
+
+ return {
+ handleDeletePet,
+ isDeleting: deletePetMutation.isPending,
+ }
+}
diff --git a/src/features/pets/hooks/delete-pet/useDeletePet.ts b/src/features/pets/hooks/delete-pet/useDeletePet.ts
new file mode 100644
index 0000000..37fd752
--- /dev/null
+++ b/src/features/pets/hooks/delete-pet/useDeletePet.ts
@@ -0,0 +1,12 @@
+import { useMutation } from "@tanstack/react-query"
+import { petsApi } from "../../api/pets-api"
+
+interface DeletePetParams {
+ id: string
+}
+
+export function useDeletePet() {
+ return useMutation({
+ mutationFn: ({ id }: DeletePetParams) => petsApi.delete(id),
+ })
+}
diff --git a/src/features/pets/hooks/pet-page-view-model/usePetPageViewModel.test.ts b/src/features/pets/hooks/pet-page-view-model/usePetPageViewModel.test.ts
index 008e79a..fb25533 100644
--- a/src/features/pets/hooks/pet-page-view-model/usePetPageViewModel.test.ts
+++ b/src/features/pets/hooks/pet-page-view-model/usePetPageViewModel.test.ts
@@ -5,6 +5,7 @@ import { usePet } from "../pet/usePet"
import * as toastUtils from "@/shared/utils/toast-utils"
import { mockNavigation } from "../../../../../jest.setup"
import axios from "axios"
+import { QueryClientProviderMock } from "@/shared/test-utils/providers/query-client-provider.mock"
jest.mock("@/features/pets/hooks/pet/usePet", () => ({
usePet: jest.fn(),
@@ -30,7 +31,10 @@ describe(usePetPageViewModel.name, () => {
})
it("should return the pet correctly", () => {
- const { result } = renderHook(() => usePetPageViewModel(petResponseMock.id))
+ const { result } = renderHook(
+ () => usePetPageViewModel(petResponseMock.id),
+ { wrapper: QueryClientProviderMock }
+ )
expect(result.current.pet).toEqual(petResponseMock)
})
@@ -39,12 +43,18 @@ describe(usePetPageViewModel.name, () => {
...baseHookMock,
isLoading: true,
})
- const { result } = renderHook(() => usePetPageViewModel(petResponseMock.id))
+ const { result } = renderHook(
+ () => usePetPageViewModel(petResponseMock.id),
+ { wrapper: QueryClientProviderMock }
+ )
expect(result.current.isLoading).toBe(true)
})
it("should return loading false when usePet is not loading", () => {
- const { result } = renderHook(() => usePetPageViewModel(petResponseMock.id))
+ const { result } = renderHook(
+ () => usePetPageViewModel(petResponseMock.id),
+ { wrapper: QueryClientProviderMock }
+ )
expect(result.current.isLoading).toBe(false)
})
@@ -56,7 +66,9 @@ describe(usePetPageViewModel.name, () => {
error,
})
;(axios.isAxiosError as unknown as jest.Mock).mockReturnValue(true)
- renderHook(() => usePetPageViewModel(petResponseMock.id))
+ renderHook(() => usePetPageViewModel(petResponseMock.id), {
+ wrapper: QueryClientProviderMock,
+ })
expect(toastUtils.showErrorToast as jest.Mock).toHaveBeenCalledWith(
"Ops! Esse pet não está disponível."
@@ -72,7 +84,9 @@ describe(usePetPageViewModel.name, () => {
error,
})
;(axios.isAxiosError as unknown as jest.Mock).mockReturnValue(true)
- renderHook(() => usePetPageViewModel(petResponseMock.id))
+ renderHook(() => usePetPageViewModel(petResponseMock.id), {
+ wrapper: QueryClientProviderMock,
+ })
expect(toastUtils.showErrorToast as jest.Mock).toHaveBeenCalled()
expect(mockNavigation.routerFunctions.push).toHaveBeenCalledWith("/pets")
diff --git a/src/features/pets/hooks/pet-page-view-model/usePetPageViewModel.ts b/src/features/pets/hooks/pet-page-view-model/usePetPageViewModel.ts
index ab89e52..4cf9a72 100644
--- a/src/features/pets/hooks/pet-page-view-model/usePetPageViewModel.ts
+++ b/src/features/pets/hooks/pet-page-view-model/usePetPageViewModel.ts
@@ -4,15 +4,20 @@ import { showErrorToast } from "@/shared/utils/toast-utils"
import { usePet } from "../pet/usePet"
import axios from "axios"
import { useNavigate } from "@/shared/hooks/useNavigate"
+import { useDeletePetHandler } from "../delete-pet-handler/useDeletePetHandler"
interface UsePetPageViewModelResult {
pet?: Pet
isLoading: boolean
+ handleDeletePet: (id: string) => void
}
export function usePetPageViewModel(id: string): UsePetPageViewModelResult {
const { toPets } = useNavigate()
- const { data, isLoading, isError, error } = usePet(id)
+ const { data, isLoading: isPetLoding, isError, error } = usePet(id)
+ const { isDeleting, handleDeletePet } = useDeletePetHandler()
+
+ const isLoading = isPetLoding || isDeleting
useEffect(() => {
if (isError && axios.isAxiosError(error)) {
@@ -29,5 +34,6 @@ export function usePetPageViewModel(id: string): UsePetPageViewModelResult {
return {
pet: data,
isLoading,
+ handleDeletePet,
}
}
diff --git a/src/features/pets/hooks/pets-page-view-model/usePetsPageViewModel.test.ts b/src/features/pets/hooks/pets-page-view-model/usePetsPageViewModel.test.ts
index 069ed29..39d6992 100644
--- a/src/features/pets/hooks/pets-page-view-model/usePetsPageViewModel.test.ts
+++ b/src/features/pets/hooks/pets-page-view-model/usePetsPageViewModel.test.ts
@@ -3,6 +3,7 @@ import { usePetsPageViewModel } from "./usePetsPageViewModel"
import { usePets } from "../pets/usePets"
import * as toastUtils from "@/shared/utils/toast-utils"
import { petPageMock } from "@/shared/test-utils/mocks/pets-mocks"
+import { QueryClientProviderMock } from "@/shared/test-utils/providers/query-client-provider.mock"
jest.mock("../pets/usePets", () => ({
usePets: jest.fn(),
@@ -25,7 +26,9 @@ describe(usePetsPageViewModel.name, () => {
})
it("should return pets page data correctly", () => {
- const { result } = renderHook(() => usePetsPageViewModel())
+ const { result } = renderHook(() => usePetsPageViewModel(), {
+ wrapper: QueryClientProviderMock,
+ })
expect(result.current.pagePetCurrent).toEqual(petPageMock)
expect(result.current.isLoading).toBe(false)
expect(result.current.page).toBe(0)
@@ -36,7 +39,9 @@ describe(usePetsPageViewModel.name, () => {
...baseHookMock,
isLoading: true,
})
- const { result } = renderHook(() => usePetsPageViewModel())
+ const { result } = renderHook(() => usePetsPageViewModel(), {
+ wrapper: QueryClientProviderMock,
+ })
expect(result.current.isLoading).toBe(true)
})
@@ -45,7 +50,9 @@ describe(usePetsPageViewModel.name, () => {
...baseHookMock,
isFetching: true,
})
- const { result } = renderHook(() => usePetsPageViewModel())
+ const { result } = renderHook(() => usePetsPageViewModel(), {
+ wrapper: QueryClientProviderMock,
+ })
expect(result.current.isLoading).toBe(true)
})
@@ -54,13 +61,17 @@ describe(usePetsPageViewModel.name, () => {
...baseHookMock,
isError: true,
})
- renderHook(() => usePetsPageViewModel())
+ renderHook(() => usePetsPageViewModel(), {
+ wrapper: QueryClientProviderMock,
+ })
expect(toastUtils.showErrorToast as jest.Mock).toHaveBeenCalled()
})
it("should change page when handleChangePage is called", () => {
const nextPage = 2
- const { result } = renderHook(() => usePetsPageViewModel())
+ const { result } = renderHook(() => usePetsPageViewModel(), {
+ wrapper: QueryClientProviderMock,
+ })
act(() => {
result.current.handleChangePage(nextPage)
})
@@ -72,7 +83,9 @@ describe(usePetsPageViewModel.name, () => {
...baseHookMock,
data: undefined,
})
- const { result } = renderHook(() => usePetsPageViewModel())
+ const { result } = renderHook(() => usePetsPageViewModel(), {
+ wrapper: QueryClientProviderMock,
+ })
expect(result.current.pagePetCurrent).toEqual({
content: [],
totalPages: 0,
diff --git a/src/features/pets/hooks/pets-page-view-model/usePetsPageViewModel.ts b/src/features/pets/hooks/pets-page-view-model/usePetsPageViewModel.ts
index c4e609c..b33dd1d 100644
--- a/src/features/pets/hooks/pets-page-view-model/usePetsPageViewModel.ts
+++ b/src/features/pets/hooks/pets-page-view-model/usePetsPageViewModel.ts
@@ -3,17 +3,21 @@ import { usePets } from "../pets/usePets"
import { PageResponse } from "@/shared/types/common.types"
import { Pet } from "../../types/pets.types"
import { showErrorToast } from "@/shared/utils/toast-utils"
+import { useDeletePetHandler } from "../delete-pet-handler/useDeletePetHandler"
interface UsePetsPageViewModelResult {
pagePetCurrent: PageResponse
isLoading: boolean
+ isDeleting: boolean
page: number
handleChangePage: (page: number) => void
+ handleDeletePet: (id: string) => void
}
export function usePetsPageViewModel(): UsePetsPageViewModelResult {
const [page, setPage] = useState(0)
const { data, isLoading: petsLoading, isFetching, isError } = usePets(page)
+ const { isDeleting, handleDeletePet } = useDeletePetHandler()
const isLoading = petsLoading || isFetching
@@ -38,7 +42,9 @@ export function usePetsPageViewModel(): UsePetsPageViewModelResult {
return {
pagePetCurrent: data ?? emptyPage,
isLoading,
+ isDeleting,
page,
handleChangePage,
+ handleDeletePet,
}
}
diff --git a/src/shared/components/dialogs/custom-dialog/CustomDialog.test.tsx b/src/shared/components/dialogs/custom-dialog/CustomDialog.test.tsx
new file mode 100644
index 0000000..ec97760
--- /dev/null
+++ b/src/shared/components/dialogs/custom-dialog/CustomDialog.test.tsx
@@ -0,0 +1,30 @@
+import { renderWithProviders } from "@/shared/test-utils/custom-render"
+import { CustomDialog } from "./CustomDialog"
+import userEvent from "@testing-library/user-event"
+import { screen } from "@testing-library/react"
+
+describe(CustomDialog.name, () => {
+ it("should call onConfirm when the confirm button is clicked", async () => {
+ const title = "Test Dialog"
+ const onConfirm = jest.fn()
+
+ renderWithProviders(
+ Abrir}
+ onConfirm={onConfirm}
+ />
+ )
+
+ await userEvent.click(screen.getByRole("button", { name: /abrir/i }))
+ expect(await screen.findByText(title)).toBeInTheDocument()
+
+ await userEvent.click(screen.getByRole("button", { name: /confirmar/i }))
+
+ expect(onConfirm).toHaveBeenCalled()
+ expect(screen.queryByText(title)).not.toBeInTheDocument()
+ })
+})
diff --git a/src/shared/components/dialogs/custom-dialog/CustomDialog.tsx b/src/shared/components/dialogs/custom-dialog/CustomDialog.tsx
new file mode 100644
index 0000000..b714f6b
--- /dev/null
+++ b/src/shared/components/dialogs/custom-dialog/CustomDialog.tsx
@@ -0,0 +1,61 @@
+"use client"
+
+import { ReactNode, useState } from "react"
+import {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "../../ui/dialog"
+import { InfoButton } from "../../buttons/info-button/InfoButton"
+import { PrimaryButton } from "../../buttons/primary-button/PrimaryButton"
+
+interface AppDialogProps extends React.ComponentProps {
+ title: string
+ description: string
+ confirmLabel: string
+ cancelLabel: string
+ triggerAction: ReactNode
+ onConfirm: () => void
+}
+
+export function CustomDialog({
+ title,
+ description,
+ confirmLabel,
+ cancelLabel,
+ triggerAction,
+ onConfirm,
+ ...props
+}: AppDialogProps) {
+ const [open, setOpen] = useState(false)
+
+ function handleConfirm() {
+ onConfirm()
+ setOpen(false)
+ }
+
+ return (
+
+ )
+}
diff --git a/src/shared/components/index.ts b/src/shared/components/index.ts
index a1d52fe..424721e 100644
--- a/src/shared/components/index.ts
+++ b/src/shared/components/index.ts
@@ -19,3 +19,4 @@ export { Header } from "./layout/header/Header"
export { ImagePlaceholder } from "./layout/image-placeholder/ImagePlaceholder"
export { CustomPagination } from "./pagination/custom-pagination/CustomPagination"
+export { CustomDialog } from "./dialogs/custom-dialog/CustomDialog"
diff --git a/src/shared/components/ui/dialog.tsx b/src/shared/components/ui/dialog.tsx
new file mode 100644
index 0000000..25ee373
--- /dev/null
+++ b/src/shared/components/ui/dialog.tsx
@@ -0,0 +1,164 @@
+"use client"
+
+import * as React from "react"
+import { Dialog as DialogPrimitive } from "radix-ui"
+
+import { cn } from "@/shared/lib/utils"
+import { Button } from "@/shared/components/ui/button"
+import { XIcon } from "lucide-react"
+
+function Dialog({
+ ...props
+}: React.ComponentProps) {
+ return
+}
+
+function DialogTrigger({
+ ...props
+}: React.ComponentProps) {
+ return
+}
+
+function DialogPortal({
+ ...props
+}: React.ComponentProps) {
+ return
+}
+
+function DialogClose({
+ ...props
+}: React.ComponentProps) {
+ return
+}
+
+function DialogOverlay({
+ className,
+ ...props
+}: React.ComponentProps) {
+ return (
+
+ )
+}
+
+function DialogContent({
+ className,
+ children,
+ showCloseButton = true,
+ ...props
+}: React.ComponentProps & {
+ showCloseButton?: boolean
+}) {
+ return (
+
+
+
+ {children}
+ {showCloseButton && (
+
+
+
+ )}
+
+
+ )
+}
+
+function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+
+ )
+}
+
+function DialogFooter({
+ className,
+ showCloseButton = false,
+ children,
+ ...props
+}: React.ComponentProps<"div"> & {
+ showCloseButton?: boolean
+}) {
+ return (
+
+ {children}
+ {showCloseButton && (
+
+
+
+ )}
+
+ )
+}
+
+function DialogTitle({
+ className,
+ ...props
+}: React.ComponentProps) {
+ return (
+
+ )
+}
+
+function DialogDescription({
+ className,
+ ...props
+}: React.ComponentProps) {
+ return (
+
+ )
+}
+
+export {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogOverlay,
+ DialogPortal,
+ DialogTitle,
+ DialogTrigger,
+}
diff --git a/src/shared/utils/toast-utils.test.ts b/src/shared/utils/toast-utils.test.ts
new file mode 100644
index 0000000..c6699f8
--- /dev/null
+++ b/src/shared/utils/toast-utils.test.ts
@@ -0,0 +1,28 @@
+import { toast } from "sonner"
+import { showErrorToast } from "./toast-utils"
+
+jest.mock("sonner", () => ({
+ toast: {
+ error: jest.fn(),
+ },
+}))
+
+describe(showErrorToast.name, () => {
+ afterEach(() => {
+ jest.clearAllMocks()
+ })
+
+ it("should display the toast with the default message if no message is provided", () => {
+ showErrorToast()
+ expect(toast.error).toHaveBeenCalledWith(
+ "Ocorreu um erro inesperado. Tente novamente mais tarde."
+ )
+ })
+
+ it("should display the toast with the custom message if provided", () => {
+ const errorMessage = "Erro interno"
+
+ showErrorToast(errorMessage)
+ expect(toast.error).toHaveBeenCalledWith(errorMessage)
+ })
+})