From 3af61c02069a7294a0fdc481748de2c287092f95 Mon Sep 17 00:00:00 2001 From: Sunil Kumar Date: Sat, 21 Sep 2024 10:09:43 +0500 Subject: [PATCH] Unit tests added for Avatar component --- src/__tests__/unit/components/Avatar.test.tsx | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 src/__tests__/unit/components/Avatar.test.tsx diff --git a/src/__tests__/unit/components/Avatar.test.tsx b/src/__tests__/unit/components/Avatar.test.tsx new file mode 100644 index 0000000..7fd41b3 --- /dev/null +++ b/src/__tests__/unit/components/Avatar.test.tsx @@ -0,0 +1,52 @@ +import React from "react" +import { render, screen, cleanup } from "@testing-library/react" +import { describe, it, expect, vi, afterEach } from "vitest" +import { Avatar } from "@/components/avatar" + +// Mock Next.js Image component +vi.mock("next/image", () => ({ + default: ({ src, alt }: { src: string; alt: string }) => {alt}, +})) +//It cleans up the dom after each test +afterEach(() => { + cleanup() +}) + +describe("Avatar", () => { + it("renders an image when src is provided", () => { + render() + const img = screen.getByRole("img") + expect(img).toBeDefined() + expect(img.getAttribute("src")).toBe("/test-image.jpg") + }) + + it("renders fallback text when src is empty", () => { + render() + const fallback = screen.getByText("T") + expect(fallback).toBeDefined() + expect(fallback.tagName).toBe("SPAN") + expect(fallback.className).includes("font-medium uppercase") + }) + + it("applies custom className", () => { + render() + const avatar = screen.getByRole("img").parentElement + expect(avatar?.className).toContain("custom-class") + }) + + it("applies different size variant", () => { + render() + render() + + const [lgAvatar, smAvatar] = screen.getAllByRole("img").map((img) => img.parentElement) + + expect(lgAvatar?.className).toContain("w-12 h-12") + expect(smAvatar?.className).toContain("w-8 h-8") + }) + + it("uses medium size as default", () => { + render() + const avatar = screen.getByRole("img").parentElement + expect(avatar?.className).toContain("w-10 h-10") + }) +})