| 1 | import { configureStore } from "@reduxjs/toolkit"; |
| 2 | import { fireEvent, render, screen } from "@testing-library/react"; |
| 3 | import { Provider } from "react-redux"; |
| 4 | import { describe, expect, it, vi } from "vitest"; |
| 5 | import { uiSlice } from "../../redux/slices/uiSlice"; |
| 6 | import ConfirmationDialog from "./ConfirmationDialog"; |
| 7 | |
| 8 | const createMockStore = () => { |
| 9 | return configureStore({ |
| 10 | reducer: { |
| 11 | uiState: uiSlice.reducer, |
| 12 | }, |
| 13 | }); |
| 14 | }; |
| 15 | |
| 16 | describe("ConfirmationDialog", () => { |
| 17 | const renderDialog = (props: any) => { |
| 18 | const store = createMockStore(); |
| 19 | return render( |
| 20 | <Provider store={store}> |
| 21 | <ConfirmationDialog {...props} /> |
| 22 | </Provider>, |
| 23 | ); |
| 24 | }; |
| 25 | |
| 26 | it("renders with default props", () => { |
| 27 | const onConfirm = vi.fn(); |
| 28 | renderDialog({ text: "Are you sure?", onConfirm }); |
| 29 | |
| 30 | expect(screen.getByText("Confirmation")).toBeInTheDocument(); |
| 31 | expect(screen.getByText("Are you sure?")).toBeInTheDocument(); |
| 32 | expect(screen.getByText("Cancel")).toBeInTheDocument(); |
| 33 | expect(screen.getByText("Confirm")).toBeInTheDocument(); |
| 34 | }); |
| 35 | |
| 36 | it("renders with custom title and confirm text", () => { |
| 37 | const onConfirm = vi.fn(); |
| 38 | renderDialog({ |
| 39 | text: "Delete item?", |
| 40 | title: "Custom Title", |
| 41 | confirmText: "Delete", |
| 42 | onConfirm, |
| 43 | }); |
| 44 | |
| 45 | expect(screen.getByText("Custom Title")).toBeInTheDocument(); |
| 46 | expect(screen.getByText("Delete item?")).toBeInTheDocument(); |
| 47 | expect(screen.getByText("Delete")).toBeInTheDocument(); |
| 48 | }); |
| 49 | |
| 50 | it("hides cancel button when hideCancelButton is true", () => { |
| 51 | const onConfirm = vi.fn(); |
| 52 | renderDialog({ |
| 53 | text: "Proceed?", |
| 54 | hideCancelButton: true, |
| 55 | onConfirm, |
| 56 | }); |
| 57 | |
| 58 | expect(screen.queryByText("Cancel")).not.toBeInTheDocument(); |
| 59 | }); |
| 60 | |
| 61 | it("calls onConfirm and dispatches actions when confirm button is clicked", () => { |
| 62 | const onConfirm = vi.fn(); |
| 63 | renderDialog({ text: "Confirm action?", onConfirm }); |
| 64 | |
| 65 | fireEvent.click(screen.getByText("Confirm")); |
| 66 | |
| 67 | expect(onConfirm).toHaveBeenCalledTimes(1); |
| 68 | }); |
| 69 | |
| 70 | it("calls onCancel and dispatches actions when cancel button is clicked", () => { |
| 71 | const onConfirm = vi.fn(); |
| 72 | const onCancel = vi.fn(); |
| 73 | renderDialog({ text: "Cancel action?", onConfirm, onCancel }); |
| 74 | |
| 75 | fireEvent.click(screen.getByText("Cancel")); |
| 76 | |
| 77 | expect(onCancel).toHaveBeenCalledTimes(1); |
| 78 | }); |
| 79 | }); |