Skip to content

Job application tracker and AI-powered job search assistant. Helps job seekers manage their search journey with AI resume review, job matching, task logging, and application analytics, all while keeping your data private.

chore: write unit tests for skill tags feature

Khuram Niaz1242b2863b0a
diff --git a/__tests__/JobDetails.spec.tsx b/__tests__/JobDetails.spec.tsx
new file mode 100644
index 0000000..f0ece3d
--- /dev/null
+++ b/__tests__/JobDetails.spec.tsx
@@ -0,0 +1,123 @@
+import React from "react";
+import JobDetails from "@/components/myjobs/JobDetails";
+import { JobResponse, Tag } from "@/models/job.model";
+import "@testing-library/jest-dom";
+import { render, screen } from "@testing-library/react";
+
+jest.mock("next/navigation", () => ({
+ useRouter: jest.fn(() => ({ back: jest.fn() })),
+}));
+
+// Stub heavy sub-components that are not under test
+jest.mock("@/components/profile/AiJobMatchSection", () => ({
+ AiJobMatchSection: () => null,
+}));
+
+jest.mock("@/components/myjobs/NotesSection", () => ({
+ NotesSection: () => null,
+}));
+
+jest.mock("@/components/TipTapContentViewer", () => ({
+ TipTapContentViewer: () => null,
+}));
+
+jest.mock("@/components/automations/MatchDetails", () => ({
+ MatchDetails: () => null,
+}));
+
+jest.mock("@/components/profile/DownloadFileButton", () => ({
+ DownloadFileButton: () => null,
+}));
+
+const makeJob = (overrides: Partial<JobResponse> = {}): JobResponse => ({
+ id: "job-1",
+ userId: "user-1",
+ JobTitle: {
+ id: "t1",
+ label: "Frontend Developer",
+ value: "frontend developer",
+ createdBy: "user-1",
+ },
+ Company: {
+ id: "c1",
+ label: "Acme Corp",
+ value: "acme corp",
+ createdBy: "user-1",
+ },
+ Status: { id: "s1", label: "Applied", value: "applied" },
+ Location: { id: "l1", label: "Remote", value: "remote", createdBy: "user-1" },
+ JobSource: {
+ id: "src1",
+ label: "LinkedIn",
+ value: "linkedin",
+ createdBy: "user-1",
+ },
+ jobType: "FT",
+ createdAt: new Date("2025-01-01"),
+ appliedDate: new Date("2025-01-15"),
+ dueDate: new Date("2099-12-31"), // far future — not expired
+ salaryRange: "3",
+ description: "<p>Job description</p>",
+ jobUrl: "",
+ applied: true,
+ tags: [],
+ ...overrides,
+});
+
+describe("JobDetails – skill badges", () => {
+ it("renders skill badges for all tags on the job", () => {
+ const tags: Tag[] = [
+ { id: "tag-1", label: "React", value: "react", createdBy: "user-1" },
+ {
+ id: "tag-2",
+ label: "TypeScript",
+ value: "typescript",
+ createdBy: "user-1",
+ },
+ { id: "tag-3", label: "Node.js", value: "node.js", createdBy: "user-1" },
+ ];
+ render(<JobDetails job={makeJob({ tags })} />);
+
+ expect(screen.getByText("React")).toBeInTheDocument();
+ expect(screen.getByText("TypeScript")).toBeInTheDocument();
+ expect(screen.getByText("Node.js")).toBeInTheDocument();
+ });
+
+ it("renders no tag badges when the job has no tags", () => {
+ render(<JobDetails job={makeJob({ tags: [] })} />);
+
+ // Verify tag area is simply absent; badges for these labels shouldn't exist
+ expect(screen.queryByText("React")).not.toBeInTheDocument();
+ expect(screen.queryByText("TypeScript")).not.toBeInTheDocument();
+ });
+
+ it("renders no tag badges when tags property is undefined", () => {
+ const job = makeJob();
+ delete job.tags;
+ render(<JobDetails job={job} />);
+
+ // Should render without crashing and show no skill badges
+ expect(screen.getByText("Frontend Developer")).toBeInTheDocument();
+ });
+
+ it("renders a single skill badge correctly", () => {
+ const tags: Tag[] = [
+ { id: "tag-1", label: "GraphQL", value: "graphql", createdBy: "user-1" },
+ ];
+ render(<JobDetails job={makeJob({ tags })} />);
+
+ expect(screen.getByText("GraphQL")).toBeInTheDocument();
+ });
+
+ it("renders each tag label exactly once", () => {
+ const tags: Tag[] = [
+ { id: "tag-1", label: "React", value: "react", createdBy: "user-1" },
+ { id: "tag-2", label: "Vue", value: "vue", createdBy: "user-1" },
+ ];
+ render(<JobDetails job={makeJob({ tags })} />);
+
+ // getAllByText returns an array; each label should appear exactly once in the badge area
+ expect(screen.getAllByText("React")).toHaveLength(1);
+ expect(screen.getAllByText("Vue")).toHaveLength(1);
+ });
+});
diff --git a/__tests__/TagInput.spec.tsx b/__tests__/TagInput.spec.tsx
new file mode 100644
index 0000000..bcdd970
--- /dev/null
+++ b/__tests__/TagInput.spec.tsx
@@ -0,0 +1,277 @@
+import React, { useState } from "react";
+import { TagInput } from "@/components/myjobs/TagInput";
+import { Tag } from "@/models/job.model";
+import "@testing-library/jest-dom";
+import { render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { createTag } from "@/actions/tag.actions";
+
+jest.mock("@/actions/tag.actions", () => ({
+ createTag: jest.fn(),
+}));
+
+jest.mock("@/components/ui/use-toast", () => ({
+ toast: jest.fn(),
+}));
+
+// Required by Radix UI Popover / Command components
+global.ResizeObserver = jest.fn().mockImplementation(() => ({
+ observe: jest.fn(),
+ unobserve: jest.fn(),
+ disconnect: jest.fn(),
+}));
+
+window.HTMLElement.prototype.scrollIntoView = jest.fn();
+window.HTMLElement.prototype.hasPointerCapture = jest.fn();
+
+document.createRange = () => {
+ const range = new Range();
+ range.getBoundingClientRect = jest.fn().mockReturnValue({
+ bottom: 0,
+ height: 0,
+ left: 0,
+ right: 0,
+ top: 0,
+ width: 0,
+ });
+ range.getClientRects = () => ({
+ item: () => null,
+ length: 0,
+ [Symbol.iterator]: jest.fn(),
+ });
+ return range;
+};
+
+// Controlled wrapper so we can track state changes
+function ControlledTagInput({
+ availableTags,
+ initialIds = [],
+}: {
+ availableTags: Tag[];
+ initialIds?: string[];
+}) {
+ const [selectedIds, setSelectedIds] = useState<string[]>(initialIds);
+ return (
+ <TagInput
+ availableTags={availableTags}
+ selectedTagIds={selectedIds}
+ onChange={setSelectedIds}
+ />
+ );
+}
+
+const MOCK_TAGS: Tag[] = [
+ { id: "tag-1", label: "React", value: "react", createdBy: "user-1" },
+ {
+ id: "tag-2",
+ label: "TypeScript",
+ value: "typescript",
+ createdBy: "user-1",
+ },
+ { id: "tag-3", label: "Node.js", value: "node.js", createdBy: "user-1" },
+];
+
+describe("TagInput Component", () => {
+ const user = userEvent.setup({ skipHover: true });
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it("renders the trigger button with default placeholder text", () => {
+ render(<ControlledTagInput availableTags={MOCK_TAGS} />);
+ expect(screen.getByRole("combobox")).toBeInTheDocument();
+ expect(screen.getByText("Search or add a skill...")).toBeInTheDocument();
+ });
+
+ it("opens the dropdown and shows available tags when the trigger is clicked", async () => {
+ render(<ControlledTagInput availableTags={MOCK_TAGS} />);
+
+ const trigger = screen.getByRole("combobox");
+ await user.click(trigger);
+
+ await waitFor(() => {
+ expect(screen.getByText("React")).toBeInTheDocument();
+ expect(screen.getByText("TypeScript")).toBeInTheDocument();
+ expect(screen.getByText("Node.js")).toBeInTheDocument();
+ });
+ });
+
+ it("selects a tag when an option is clicked and renders it as a badge", async () => {
+ render(<ControlledTagInput availableTags={MOCK_TAGS} />);
+
+ await user.click(screen.getByRole("combobox"));
+ await user.click(await screen.findByRole("option", { name: "React" }));
+
+ await waitFor(() => {
+ // Badge should appear in the selected tags area
+ const badges = screen.getAllByText("React");
+ expect(badges.length).toBeGreaterThan(0);
+ });
+ });
+
+ it("closes the popover after selecting an existing tag", async () => {
+ render(<ControlledTagInput availableTags={MOCK_TAGS} />);
+
+ await user.click(screen.getByRole("combobox"));
+ await user.click(await screen.findByRole("option", { name: "TypeScript" }));
+
+ await waitFor(() => {
+ // Options list should be gone
+ expect(
+ screen.queryByRole("option", { name: "React" }),
+ ).not.toBeInTheDocument();
+ });
+ });
+
+ it("excludes already-selected tags from the dropdown options", async () => {
+ render(
+ <ControlledTagInput availableTags={MOCK_TAGS} initialIds={["tag-1"]} />,
+ );
+
+ await user.click(screen.getByRole("combobox"));
+
+ await waitFor(() => {
+ expect(
+ screen.queryByRole("option", { name: "React" }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.getByRole("option", { name: "TypeScript" }),
+ ).toBeInTheDocument();
+ });
+ });
+
+ it("removes a tag badge when the remove button is clicked", async () => {
+ render(
+ <ControlledTagInput
+ availableTags={MOCK_TAGS}
+ initialIds={["tag-1", "tag-2"]}
+ />,
+ );
+
+ const removeReactBtn = screen.getByRole("button", {
+ name: /remove react/i,
+ });
+ await user.click(removeReactBtn);
+
+ await waitFor(() => {
+ expect(
+ screen.queryByRole("button", { name: /remove react/i }),
+ ).not.toBeInTheDocument();
+ // TypeScript badge should still be present
+ expect(
+ screen.getByRole("button", { name: /remove typescript/i }),
+ ).toBeInTheDocument();
+ });
+ });
+
+ it("renders selected tag badges for pre-selected tags", () => {
+ render(
+ <ControlledTagInput
+ availableTags={MOCK_TAGS}
+ initialIds={["tag-1", "tag-3"]}
+ />,
+ );
+
+ expect(
+ screen.getByRole("button", { name: /remove react/i }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: /remove node.js/i }),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: /remove typescript/i }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("shows a create option when typed value has no exact match", async () => {
+ render(<ControlledTagInput availableTags={MOCK_TAGS} />);
+
+ await user.click(screen.getByRole("combobox"));
+ await user.type(screen.getByPlaceholderText("Type a skill..."), "GraphQL");
+
+ await waitFor(() => {
+ expect(screen.getByText(/Create "GraphQL"/i)).toBeInTheDocument();
+ });
+ });
+
+ it("hides the create option when the typed value exactly matches an existing tag", async () => {
+ render(<ControlledTagInput availableTags={MOCK_TAGS} />);
+
+ await user.click(screen.getByRole("combobox"));
+ await user.type(screen.getByPlaceholderText("Type a skill..."), "react");
+
+ await waitFor(() => {
+ expect(screen.queryByText(/Create "react"/i)).not.toBeInTheDocument();
+ });
+ });
+
+ it("calls createTag with the typed label and closes the popover on success", async () => {
+ const newTag: Tag = {
+ id: "tag-99",
+ label: "GraphQL",
+ value: "graphql",
+ createdBy: "user-1",
+ };
+ (createTag as jest.Mock).mockResolvedValue({ success: true, data: newTag });
+
+ render(<ControlledTagInput availableTags={MOCK_TAGS} />);
+
+ await user.click(screen.getByRole("combobox"));
+ await user.type(screen.getByPlaceholderText("Type a skill..."), "GraphQL");
+ await user.click(await screen.findByText(/Create "GraphQL"/i));
+
+ await waitFor(() => {
+ expect(createTag).toHaveBeenCalledWith("GraphQL");
+ // Popover should be closed
+ expect(
+ screen.queryByRole("option", { name: "React" }),
+ ).not.toBeInTheDocument();
+ });
+ });
+
+ it("shows a toast error and keeps the popover open when createTag fails", async () => {
+ const { toast } = require("@/components/ui/use-toast");
+ (createTag as jest.Mock).mockResolvedValue({
+ success: false,
+ message: "Server error",
+ });
+
+ render(<ControlledTagInput availableTags={MOCK_TAGS} />);
+
+ await user.click(screen.getByRole("combobox"));
+ await user.type(screen.getByPlaceholderText("Type a skill..."), "GraphQL");
+ await user.click(await screen.findByText(/Create "GraphQL"/i));
+
+ await waitFor(() => {
+ expect(createTag).toHaveBeenCalledWith("GraphQL");
+ expect(toast).toHaveBeenCalledWith(
+ expect.objectContaining({
+ variant: "destructive",
+ description: "Server error",
+ }),
+ );
+ });
+ });
+
+ it("disables the trigger and shows max-reached message when 10 tags are selected", () => {
+ const tenTagIds = Array.from({ length: 10 }, (_, i) => `tag-${i + 100}`);
+ const tenTags: Tag[] = tenTagIds.map((id, i) => ({
+ id,
+ label: `Skill ${i + 1}`,
+ value: `skill-${i + 1}`,
+ createdBy: "user-1",
+ }));
+
+ render(
+ <ControlledTagInput
+ availableTags={[...MOCK_TAGS, ...tenTags]}
+ initialIds={tenTagIds}
+ />,
+ );
+
+ const trigger = screen.getByRole("combobox");
+ expect(trigger).toBeDisabled();
+ expect(screen.getByText("Max 10 skills reached")).toBeInTheDocument();
+ });
+});
diff --git a/__tests__/tag.actions.spec.ts b/__tests__/tag.actions.spec.ts
new file mode 100644
index 0000000..0c792f6
--- /dev/null
+++ b/__tests__/tag.actions.spec.ts
@@ -0,0 +1,248 @@
+import {
+ getAllTags,
+ getTagList,
+ createTag,
+ deleteTagById,
+} from "@/actions/tag.actions";
+import { getCurrentUser } from "@/utils/user.utils";
+import { PrismaClient } from "@prisma/client";
+
+const prisma = new PrismaClient();
+
+jest.mock("@prisma/client", () => {
+ const mPrismaClient = {
+ tag: {
+ findMany: jest.fn(),
+ count: jest.fn(),
+ upsert: jest.fn(),
+ delete: jest.fn(),
+ },
+ job: {
+ count: jest.fn(),
+ },
+ };
+ return { PrismaClient: jest.fn(() => mPrismaClient) };
+});
+
+jest.mock("@/utils/user.utils", () => ({
+ getCurrentUser: jest.fn(),
+}));
+
+describe("Tag Actions", () => {
+ const mockUser = { id: "user-id" };
+
+ const mockTag = {
+ id: "tag-1",
+ label: "React",
+ value: "react",
+ createdBy: mockUser.id,
+ };
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ // getAllTags
+ describe("getAllTags", () => {
+ it("should return all tags for the authenticated user", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(mockUser);
+ const mockTags = [
+ mockTag,
+ { ...mockTag, id: "tag-2", label: "TypeScript", value: "typescript" },
+ ];
+ (prisma.tag.findMany as jest.Mock).mockResolvedValue(mockTags);
+
+ const result = await getAllTags();
+
+ expect(result).toEqual(mockTags);
+ expect(prisma.tag.findMany).toHaveBeenCalledWith({
+ where: { createdBy: mockUser.id },
+ orderBy: { label: "asc" },
+ });
+ });
+
+ it("should return error for unauthenticated user", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(null);
+
+ const result = await getAllTags();
+
+ expect(result).toEqual({ success: false, message: "Not authenticated" });
+ expect(prisma.tag.findMany).not.toHaveBeenCalled();
+ });
+
+ it("should handle database errors", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(mockUser);
+ (prisma.tag.findMany as jest.Mock).mockRejectedValue(
+ new Error("DB error"),
+ );
+
+ const result = await getAllTags();
+
+ expect(result).toEqual({ success: false, message: "DB error" });
+ });
+ });
+
+ // getTagList
+ describe("getTagList", () => {
+ it("should return paginated tag list with counts", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(mockUser);
+ const mockData = [{ ...mockTag, _count: { jobs: 3 } }];
+ (prisma.tag.findMany as jest.Mock).mockResolvedValue(mockData);
+ (prisma.tag.count as jest.Mock).mockResolvedValue(1);
+
+ const result = await getTagList(1, 10);
+
+ expect(result).toEqual({ data: mockData, total: 1 });
+ expect(prisma.tag.findMany).toHaveBeenCalledWith(
+ expect.objectContaining({
+ where: { createdBy: mockUser.id },
+ skip: 0,
+ take: 10,
+ orderBy: { label: "asc" },
+ }),
+ );
+ });
+
+ it("should calculate skip correctly for page 2", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(mockUser);
+ (prisma.tag.findMany as jest.Mock).mockResolvedValue([]);
+ (prisma.tag.count as jest.Mock).mockResolvedValue(0);
+
+ await getTagList(2, 10);
+
+ expect(prisma.tag.findMany).toHaveBeenCalledWith(
+ expect.objectContaining({ skip: 10, take: 10 }),
+ );
+ });
+
+ it("should return error for unauthenticated user", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(null);
+
+ const result = await getTagList(1, 10);
+
+ expect(result).toEqual({ success: false, message: "Not authenticated" });
+ expect(prisma.tag.findMany).not.toHaveBeenCalled();
+ });
+
+ it("should handle database errors", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(mockUser);
+ (prisma.tag.findMany as jest.Mock).mockRejectedValue(
+ new Error("DB error"),
+ );
+
+ const result = await getTagList(1, 10);
+
+ expect(result).toEqual({ success: false, message: "DB error" });
+ });
+ });
+
+ // createTag
+ describe("createTag", () => {
+ it("should upsert and return the tag on success", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(mockUser);
+ (prisma.tag.upsert as jest.Mock).mockResolvedValue(mockTag);
+
+ const result = await createTag("React");
+
+ expect(result).toEqual({ data: mockTag, success: true });
+ expect(prisma.tag.upsert).toHaveBeenCalledWith({
+ where: { value_createdBy: { value: "react", createdBy: mockUser.id } },
+ update: {},
+ create: { label: "React", value: "react", createdBy: mockUser.id },
+ });
+ });
+
+ it("should trim label and lowercase the value", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(mockUser);
+ (prisma.tag.upsert as jest.Mock).mockResolvedValue(mockTag);
+
+ await createTag(" React ");
+
+ expect(prisma.tag.upsert).toHaveBeenCalledWith(
+ expect.objectContaining({
+ create: expect.objectContaining({ label: "React", value: "react" }),
+ }),
+ );
+ });
+
+ it("should return error for empty label", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(mockUser);
+
+ const result = await createTag(" ");
+
+ expect(result).toEqual({
+ success: false,
+ message: "Tag label cannot be empty.",
+ });
+ expect(prisma.tag.upsert).not.toHaveBeenCalled();
+ });
+
+ it("should return error for unauthenticated user", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(null);
+
+ const result = await createTag("React");
+
+ expect(result).toEqual({ success: false, message: "Not authenticated" });
+ expect(prisma.tag.upsert).not.toHaveBeenCalled();
+ });
+
+ it("should handle database errors", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(mockUser);
+ (prisma.tag.upsert as jest.Mock).mockRejectedValue(new Error("DB error"));
+
+ const result = await createTag("React");
+
+ expect(result).toEqual({ success: false, message: "DB error" });
+ });
+ });
+
+ // deleteTagById
+ describe("deleteTagById", () => {
+ it("should delete a tag that has no linked jobs", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(mockUser);
+ (prisma.job.count as jest.Mock).mockResolvedValue(0);
+ (prisma.tag.delete as jest.Mock).mockResolvedValue(mockTag);
+
+ const result = await deleteTagById("tag-1");
+
+ expect(result).toEqual({ res: mockTag, success: true });
+ expect(prisma.tag.delete).toHaveBeenCalledWith({
+ where: { id: "tag-1", createdBy: mockUser.id },
+ });
+ });
+
+ it("should return error when tag is linked to one or more jobs", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(mockUser);
+ (prisma.job.count as jest.Mock).mockResolvedValue(3);
+
+ const result = await deleteTagById("tag-1");
+
+ expect(result).toEqual({
+ success: false,
+ message:
+ "Skill tag cannot be deleted because it is linked to 3 job(s).",
+ });
+ expect(prisma.tag.delete).not.toHaveBeenCalled();
+ });
+
+ it("should return error for unauthenticated user", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(null);
+
+ const result = await deleteTagById("tag-1");
+
+ expect(result).toEqual({ success: false, message: "Not authenticated" });
+ expect(prisma.job.count).not.toHaveBeenCalled();
+ expect(prisma.tag.delete).not.toHaveBeenCalled();
+ });
+
+ it("should handle database errors during deletion", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(mockUser);
+ (prisma.job.count as jest.Mock).mockResolvedValue(0);
+ (prisma.tag.delete as jest.Mock).mockRejectedValue(new Error("DB error"));
+
+ const result = await deleteTagById("tag-1");
+
+ expect(result).toEqual({ success: false, message: "DB error" });
+ });
+ });
+});