Skip to content

Commit

Permalink
Added Unit Tests for Avatar component (#131)
Browse files Browse the repository at this point in the history
  • Loading branch information
sunilk429 authored Sep 21, 2024
1 parent f16ae8c commit 0e978dd
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions src/__tests__/unit/components/Avatar.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { cleanup, render, screen } from "@testing-library/react"
import { afterEach, describe, expect, it, vi } from "vitest"

import { Avatar } from "@/components/avatar"

// Mock Next.js Image component
vi.mock("next/image", () => ({
default: ({ src, alt }: { src: string; alt: string }) => <img src={src} alt={alt} />,
}))
//It cleans up the dom after each test
afterEach(() => {
cleanup()
})

describe("Avatar", () => {
it("renders an image when src is provided", () => {
render(<Avatar src="/test-image.jpg" alt="Test Avatar" />)
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(<Avatar src="" alt="Test Avatar" fallback="T" />)
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(<Avatar src="/test-image.jpg" alt="Test Avatar" className="custom-class" />)
const avatar = screen.getByRole("img").parentElement
expect(avatar?.className).toContain("custom-class")
})

it("applies different size variant", () => {
render(<Avatar src="/test-image.jpg" alt="Test Avatar" size="lg" />)
render(<Avatar src="/test-image.jpg" alt="Test Avatar" size="sm" />)

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(<Avatar src="/test-image.jpg" alt="Test Avatar" />)
const avatar = screen.getByRole("img").parentElement
expect(avatar?.className).toContain("w-10 h-10")
})
})

0 comments on commit 0e978dd

Please sign in to comment.