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.

feat: Add tests for MyJobsTable component including job rendering and actions

Khuram Niazc831e3d2bd23
diff --git a/__tests__/AddJob.spec.tsx b/__tests__/AddJob.spec.tsx
index 2a3daa5..9a427be 100644
--- a/__tests__/AddJob.spec.tsx
+++ b/__tests__/AddJob.spec.tsx
@@ -6,13 +6,27 @@ import { screen, render, waitFor } from "@testing-library/react";
import { getCurrentUser } from "@/utils/user.utils";
import userEvent from "@testing-library/user-event";
import { format } from "date-fns";
-import { addJob } from "@/actions/job.actions";
+import { addJob, updateJob } from "@/actions/job.actions";
+import { toast } from "@/components/ui/use-toast";
+import type { JobResponse } from "@/models/job.model";
vi.mock("@/utils/user.utils", () => ({
getCurrentUser: vi.fn(),
}));
vi.mock("@/actions/job.actions", () => ({
addJob: vi.fn().mockResolvedValue({ success: true }),
+ updateJob: vi.fn().mockResolvedValue({ success: true }),
+}));
+
+vi.mock("@/actions/note.actions", () => ({
+ getNotesByJobId: vi.fn().mockResolvedValue({ success: true, data: [] }),
+ addNote: vi.fn(),
+ updateNote: vi.fn(),
+ deleteNote: vi.fn(),
+}));
+
+vi.mock("@/components/ui/use-toast", () => ({
+ toast: vi.fn(),
}));
vi.mock("next/navigation", () => ({
@@ -253,3 +267,168 @@ describe("AddJob Component", () => {
});
});
});
+
+describe("AddJob Component - Edit Mode", () => {
+ const mockJobStatuses = JOB_STATUSES;
+ const mockJobSources = JOB_SOURCES;
+ const mockResetEditJob = vi.fn();
+ window.HTMLElement.prototype.scrollIntoView = vi.fn();
+ window.HTMLElement.prototype.hasPointerCapture = vi.fn();
+
+ const editJob = {
+ id: "job-edit-1",
+ userId: "user-id",
+ JobTitle: { id: "1xx", label: "Full Stack Developer", value: "full stack developer" },
+ Company: { id: "2zz", label: "Amazon", value: "amazon", logoUrl: "" },
+ Location: { id: "1yy", label: "Remote", value: "remote" },
+ JobSource: { id: "1359dac4-a397-4461-b747-382706dcbe79", label: "Indeed", value: "indeed" },
+ Status: { id: "5e7c6e8c-83e6-46e3-bf01-db8f0b503399", label: "Applied", value: "applied" },
+ jobType: "FT",
+ createdAt: new Date("2024-06-01"),
+ appliedDate: new Date("2024-06-05"),
+ dueDate: new Date("2024-06-20"),
+ salaryRange: "2",
+ description: "<p>Existing job description</p>",
+ jobUrl: "https://example.com/job",
+ applied: true,
+ } as unknown as JobResponse;
+
+ async function renderEditMode() {
+ const mockCompanies = (await getMockList(1, 10, "companies")).data;
+ const mockJobTitles = (await getMockList(1, 10, "jobTitles")).data;
+ const mockLocations = (await getMockList(1, 10, "locations")).data;
+ vi.clearAllMocks();
+ return render(
+ <AddJob
+ jobStatuses={mockJobStatuses}
+ companies={mockCompanies}
+ jobTitles={mockJobTitles}
+ locations={mockLocations}
+ jobSources={mockJobSources}
+ tags={[]}
+ editJob={editJob}
+ resetEditJob={mockResetEditJob}
+ />,
+ );
+ }
+
+ it("opens automatically with title 'Edit Job' and pre-fills the form from editJob", async () => {
+ await renderEditMode();
+
+ const dialogTitle = screen.getByTestId("add-job-dialog-title");
+ expect(dialogTitle).toHaveTextContent("Edit Job");
+
+ expect(screen.getByLabelText("Job Title")).toHaveTextContent(
+ "Full Stack Developer",
+ );
+ expect(screen.getByLabelText("Company")).toHaveTextContent("Amazon");
+ expect(screen.getByLabelText("Job Location")).toHaveTextContent("Remote");
+ expect(screen.getByLabelText("Job Source")).toHaveTextContent("Indeed");
+ expect(screen.getByLabelText("Status")).toHaveTextContent("Applied");
+ expect(screen.getByLabelText("Job URL")).toHaveValue(
+ "https://example.com/job",
+ );
+
+ const appliedSwitch = screen.getByRole("switch");
+ expect(appliedSwitch).toBeChecked();
+ });
+
+ it("calls updateJob (not addJob) with the job id when saving an edited job", async () => {
+ await renderEditMode();
+
+ await waitFor(() => {
+ expect(screen.getByTestId("add-job-dialog-title")).toHaveTextContent(
+ "Edit Job",
+ );
+ });
+
+ const dialog = await screen.findByRole("dialog");
+ const saveBtn = screen.getByTestId("save-job-btn");
+ const user = userEvent.setup({ skipHover: true });
+ await user.click(saveBtn);
+
+ await waitFor(() => {
+ expect(updateJob).toHaveBeenCalledTimes(1);
+ expect(addJob).not.toHaveBeenCalled();
+ expect(dialog).not.toBeInTheDocument();
+ expect(updateJob).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: "job-edit-1",
+ title: "1xx",
+ company: "2zz",
+ location: "1yy",
+ source: "1359dac4-a397-4461-b747-382706dcbe79",
+ status: "5e7c6e8c-83e6-46e3-bf01-db8f0b503399",
+ }),
+ );
+ });
+ });
+});
+
+describe("AddJob Component - Error Handling", () => {
+ const mockJobStatuses = JOB_STATUSES;
+ const mockJobSources = JOB_SOURCES;
+ const mockResetEditJob = vi.fn();
+ window.HTMLElement.prototype.scrollIntoView = vi.fn();
+ window.HTMLElement.prototype.hasPointerCapture = vi.fn();
+
+ it("shows a destructive toast when addJob fails", async () => {
+ const mockCompanies = (await getMockList(1, 10, "companies")).data;
+ const mockJobTitles = (await getMockList(1, 10, "jobTitles")).data;
+ const mockLocations = (await getMockList(1, 10, "locations")).data;
+ vi.clearAllMocks();
+ (addJob as any).mockResolvedValueOnce({
+ success: false,
+ message: "Failed to save job",
+ });
+
+ render(
+ <AddJob
+ jobStatuses={mockJobStatuses}
+ companies={mockCompanies}
+ jobTitles={mockJobTitles}
+ locations={mockLocations}
+ jobSources={mockJobSources}
+ tags={[]}
+ editJob={null}
+ resetEditJob={mockResetEditJob}
+ />,
+ );
+ const user = userEvent.setup({ skipHover: true });
+ await user.click(screen.getByTestId("add-job-btn"));
+
+ const jobTitleInput = screen.getByRole("combobox", { name: /job title/i });
+ await user.click(jobTitleInput);
+ await user.click(screen.getByRole("option", { name: "Full Stack Developer" }));
+
+ const companyInput = screen.getByRole("combobox", { name: /company/i });
+ await user.click(companyInput);
+ await user.click(screen.getByRole("option", { name: "Amazon" }));
+
+ const locationInput = screen.getByRole("combobox", { name: /job location/i });
+ await user.click(locationInput);
+ await user.click(screen.getByRole("option", { name: "Remote" }));
+
+ const sourceInput = screen.getByRole("combobox", { name: /job source/i });
+ await user.click(sourceInput);
+ await user.click(screen.getByRole("option", { name: "Indeed" }));
+
+ const editableDiv = screen.getByLabelText("Job Description");
+ const pTag = editableDiv.querySelector("div > p");
+ if (pTag) {
+ pTag.textContent = "Some description";
+ }
+
+ await user.click(screen.getByTestId("save-job-btn"));
+
+ await waitFor(() => {
+ expect(toast).toHaveBeenCalledWith(
+ expect.objectContaining({
+ variant: "destructive",
+ title: "Error!",
+ description: "Failed to save job",
+ }),
+ );
+ });
+ });
+});
diff --git a/__tests__/MyJobsTable.spec.tsx b/__tests__/MyJobsTable.spec.tsx
new file mode 100644
index 0000000..6c67793
--- /dev/null
+++ b/__tests__/MyJobsTable.spec.tsx
@@ -0,0 +1,217 @@
+import { render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import MyJobsTable from "@/components/myjobs/MyJobsTable";
+import type { JobResponse, JobStatus } from "@/models/job.model";
+
+const mockPush = vi.fn();
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ push: mockPush }),
+}));
+
+window.HTMLElement.prototype.scrollIntoView = vi.fn();
+window.HTMLElement.prototype.hasPointerCapture = vi.fn();
+window.HTMLElement.prototype.releasePointerCapture = vi.fn();
+
+const mockStatuses: JobStatus[] = [
+ { id: "1", label: "Applied", value: "applied" },
+ { id: "2", label: "Interview", value: "interview" },
+ { id: "3", label: "Draft", value: "draft" },
+];
+
+function makeJob(overrides: Partial<JobResponse> = {}): JobResponse {
+ return {
+ id: "job-1",
+ userId: "user-1",
+ JobTitle: { id: "1", label: "Software Engineer", value: "software engineer" },
+ Company: { id: "1", label: "Acme Corp", value: "acme corp", logoUrl: "" },
+ Status: { id: "1", label: "Applied", value: "applied" },
+ Location: { id: "1", label: "Remote", value: "remote" },
+ JobSource: { id: "1", label: "Indeed", value: "indeed" },
+ jobType: "FT",
+ createdAt: new Date("2024-06-01"),
+ appliedDate: new Date("2024-06-01"),
+ dueDate: new Date("2099-01-01"),
+ salaryRange: "",
+ description: "",
+ jobUrl: "",
+ applied: true,
+ ...overrides,
+ } as JobResponse;
+}
+
+function renderTable(jobs: JobResponse[], overrides: Partial<React.ComponentProps<typeof MyJobsTable>> = {}) {
+ const deleteJob = vi.fn();
+ const editJob = vi.fn();
+ const onChangeJobStatus = vi.fn();
+ const onAddNote = vi.fn();
+ const props: React.ComponentProps<typeof MyJobsTable> = {
+ jobs,
+ jobStatuses: mockStatuses,
+ deleteJob,
+ editJob,
+ onChangeJobStatus,
+ onAddNote,
+ ...overrides,
+ };
+ const result = render(<MyJobsTable {...props} />);
+ return { ...result, deleteJob, editJob, onChangeJobStatus, onAddNote };
+}
+
+describe("MyJobsTable", () => {
+ it("renders a row per job with title, company, and location", () => {
+ renderTable([makeJob()]);
+
+ expect(screen.getByText("Software Engineer")).toBeInTheDocument();
+ expect(screen.getByText("Acme Corp")).toBeInTheDocument();
+ expect(screen.getByText("Remote")).toBeInTheDocument();
+ expect(screen.getByText("Applied")).toBeInTheDocument();
+ });
+
+ it("shows a Dismissed badge for discovered jobs regardless of status", () => {
+ renderTable([makeJob({ discoveryStatus: "dismissed", Status: { id: "1", label: "Applied", value: "applied" } })]);
+
+ expect(screen.getByText("Dismissed")).toBeInTheDocument();
+ expect(screen.queryByText("Applied")).not.toBeInTheDocument();
+ });
+
+ it("shows an Expired badge for past-due draft jobs", () => {
+ renderTable([
+ makeJob({
+ dueDate: new Date("2000-01-01"),
+ Status: { id: "3", label: "Draft", value: "draft" },
+ }),
+ ]);
+
+ expect(screen.getByText("Expired")).toBeInTheDocument();
+ });
+
+ it("does not show Expired for past-due jobs that are not drafts", () => {
+ renderTable([
+ makeJob({
+ dueDate: new Date("2000-01-01"),
+ Status: { id: "1", label: "Applied", value: "applied" },
+ }),
+ ]);
+
+ expect(screen.queryByText("Expired")).not.toBeInTheDocument();
+ expect(screen.getByText("Applied")).toBeInTheDocument();
+ });
+
+ it("renders a match score when present, and a dash otherwise", () => {
+ const { rerender } = renderTable([makeJob({ matchScore: 87 })]);
+ expect(screen.getByText("87%")).toBeInTheDocument();
+
+ rerender(
+ <MyJobsTable
+ jobs={[makeJob({ matchScore: null })]}
+ jobStatuses={mockStatuses}
+ deleteJob={vi.fn()}
+ editJob={vi.fn()}
+ onChangeJobStatus={vi.fn()}
+ onAddNote={vi.fn()}
+ />,
+ );
+ expect(screen.getByText("-")).toBeInTheDocument();
+ });
+
+ it("shows a notes count badge only when the job has notes", () => {
+ const { rerender } = renderTable([makeJob({ _count: { Notes: 3 } })]);
+ expect(screen.getByText("3")).toBeInTheDocument();
+
+ rerender(
+ <MyJobsTable
+ jobs={[makeJob({ _count: { Notes: 0 } })]}
+ jobStatuses={mockStatuses}
+ deleteJob={vi.fn()}
+ editJob={vi.fn()}
+ onChangeJobStatus={vi.fn()}
+ onAddNote={vi.fn()}
+ />,
+ );
+ expect(screen.queryByText("0")).not.toBeInTheDocument();
+ });
+
+ describe("row actions menu", () => {
+ const user = userEvent.setup();
+
+ it("navigates to job details when View Details is clicked", async () => {
+ renderTable([makeJob()]);
+
+ await user.click(screen.getByTestId("job-actions-menu-btn"));
+ await user.click(screen.getByText("View Details"));
+
+ expect(mockPush).toHaveBeenCalledWith("/dashboard/myjobs/job-1");
+ });
+
+ it("calls editJob with the job id when Edit Job is clicked", async () => {
+ const { editJob } = renderTable([makeJob()]);
+
+ await user.click(screen.getByTestId("job-actions-menu-btn"));
+ await user.click(screen.getByText("Edit Job"));
+
+ expect(editJob).toHaveBeenCalledWith("job-1");
+ });
+
+ it("calls onAddNote with the job id when Add a Note is clicked", async () => {
+ const { onAddNote } = renderTable([makeJob()]);
+
+ await user.click(screen.getByTestId("job-actions-menu-btn"));
+ await user.click(screen.getByText("Add a Note"));
+
+ expect(onAddNote).toHaveBeenCalledWith("job-1");
+ });
+
+ it("opens the delete confirmation dialog and calls deleteJob on confirm", async () => {
+ const { deleteJob } = renderTable([makeJob()]);
+
+ await user.click(screen.getByTestId("job-actions-menu-btn"));
+ await user.click(screen.getByText("Delete"));
+
+ expect(
+ screen.getByText("Are you sure you want to delete this job?"),
+ ).toBeInTheDocument();
+
+ await user.click(screen.getByRole("button", { name: "Delete" }));
+
+ expect(deleteJob).toHaveBeenCalledWith("job-1");
+ });
+
+ // The "Change status" item is a Radix submenu trigger; opening/selecting
+ // via pointer clicks is flaky in jsdom, so drive it with the keyboard,
+ // which is how Radix menus are designed to be operated.
+ const openChangeStatusSubmenu = async () => {
+ await user.click(screen.getByTestId("job-actions-menu-btn"));
+ await user.keyboard("{ArrowDown}{ArrowDown}{ArrowDown}{ArrowDown}");
+ await user.keyboard("{ArrowRight}");
+ await screen.findByText("Interview");
+ };
+
+ it("disables the current status option in the Change status submenu", async () => {
+ renderTable([makeJob({ Status: { id: "1", label: "Applied", value: "applied" } })]);
+
+ await openChangeStatusSubmenu();
+
+ const appliedOption = screen.getAllByText("Applied").find(
+ (el) => el.closest('[role="menuitem"]'),
+ );
+ expect(appliedOption?.closest('[role="menuitem"]')).toHaveAttribute(
+ "data-disabled",
+ );
+ });
+
+ it("calls onChangeJobStatus with the job id and selected status", async () => {
+ const { onChangeJobStatus } = renderTable([
+ makeJob({ Status: { id: "1", label: "Applied", value: "applied" } }),
+ ]);
+
+ await openChangeStatusSubmenu();
+ await user.keyboard("{Enter}");
+
+ expect(onChangeJobStatus).toHaveBeenCalledWith("job-1", {
+ id: "2",
+ label: "Interview",
+ value: "interview",
+ });
+ });
+ });
+});