From d5118881d8b350b7cb94ca4da4c4e02ec0993552 Mon Sep 17 00:00:00 2001
From: sunilk429 <160393886+sunilk429@users.noreply.github.com>
Date: Mon, 7 Oct 2024 23:32:37 +0500
Subject: [PATCH] Added Unit Test for BackButton component (#136)
---
.../unit/components/BackButton.test.tsx | 60 +++++++++++++++++++
1 file changed, 60 insertions(+)
create mode 100644 src/__tests__/unit/components/BackButton.test.tsx
diff --git a/src/__tests__/unit/components/BackButton.test.tsx b/src/__tests__/unit/components/BackButton.test.tsx
new file mode 100644
index 0000000..d88e89b
--- /dev/null
+++ b/src/__tests__/unit/components/BackButton.test.tsx
@@ -0,0 +1,60 @@
+import { cleanup, fireEvent, render, screen } from "@testing-library/react"
+import { useRouter } from "next/navigation"
+import { afterEach, describe, expect, it, vi } from "vitest"
+
+import { BackButton } from "@/components/back-button"
+// Mock the next/navigation useRouter hook
+const mockPush = vi.fn()
+const mockBack = vi.fn()
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({
+ push: mockPush,
+ back: mockBack,
+ }),
+}))
+describe("BackButton Component", () => {
+ afterEach(() => {
+ cleanup()
+ })
+
+ it("should navigate back if no route prop is provided", () => {
+ const { back } = useRouter()
+ render()
+
+ const button = screen.getByRole("button", { name: /back/i })
+ fireEvent.click(button)
+
+ expect(back).toHaveBeenCalledTimes(1) // Check that 'back' is called
+ })
+
+ it("should navigate to the provided route when route prop is specified", () => {
+ const { push } = useRouter()
+ render()
+
+ const button = screen.getByRole("button", { name: /back/i })
+ fireEvent.click(button)
+
+ expect(push).toHaveBeenCalledWith("/home") // Check that 'push' is called with the correct route
+ })
+
+ it('should render with default label "Back" if no label is provided', () => {
+ render()
+
+ const button = screen.getByRole("button", { name: /back/i })
+ expect(button).toBeTruthy()
+ })
+
+ it("should render the correct label when label prop is provided", () => {
+ render()
+
+ const button = screen.getByRole("button", { name: /go home/i })
+ expect(button).toBeTruthy()
+ })
+
+ it("should render left arrow icon", () => {
+ render()
+ const arrowLeftIcon = document.querySelector("svg")
+ expect(arrowLeftIcon).toBeTruthy()
+ })
+})