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.

AddJob form tests

Khuram Niaz8bc249e57863
diff --git a/__tests__/AddCompany.spec.tsx b/__tests__/AddCompany.spec.tsx
index c2638b3..7066172 100644
--- a/__tests__/AddCompany.spec.tsx
+++ b/__tests__/AddCompany.spec.tsx
@@ -1,13 +1,7 @@
import { addCompany, updateCompany } from "@/actions/company.actions";
import AddCompany from "@/components/admin/AddCompany";
import "@testing-library/jest-dom";
-import {
- screen,
- render,
- waitFor,
- fireEvent,
- act,
-} from "@testing-library/react";
+import { screen, render, waitFor, fireEvent } from "@testing-library/react";
jest.mock("@/actions/company.actions", () => ({
addCompany: jest.fn(),
diff --git a/__tests__/AddJob.spec.tsx b/__tests__/AddJob.spec.tsx
new file mode 100644
index 0000000..5aa97de
--- /dev/null
+++ b/__tests__/AddJob.spec.tsx
@@ -0,0 +1,103 @@
+import { AddJob } from "@/components/myjobs/AddJob";
+import { JOB_SOURCES } from "@/lib/data/jobSourcesData";
+import { JOB_STATUSES } from "@/lib/data/jobStatusesData";
+import { getMockList } from "@/lib/mock.utils";
+import "@testing-library/jest-dom";
+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";
+
+jest.mock("@/utils/user.utils", () => ({
+ getCurrentUser: jest.fn(),
+}));
+
+global.ResizeObserver = jest.fn().mockImplementation(() => ({
+ observe: jest.fn(),
+ unobserve: jest.fn(),
+ disconnect: jest.fn(),
+}));
+
+describe("AddCompany Component", () => {
+ const mockUser = { id: "user-id" };
+ const mockJobStatuses = JOB_STATUSES;
+ const mockJobSources = JOB_SOURCES;
+ const mockResetEditJob = jest.fn();
+ const user = userEvent.setup();
+ let container: HTMLElement | null;
+
+ beforeEach(async () => {
+ jest.clearAllMocks();
+ const mockCompanies = (await getMockList(1, 10, "companies")).data;
+ const mockJobTitles = (await getMockList(1, 10, "jobTitles")).data;
+ const mockLocations = (await getMockList(1, 10, "locations")).data;
+ render(
+ <AddJob
+ jobStatuses={mockJobStatuses}
+ companies={mockCompanies}
+ jobTitles={mockJobTitles}
+ locations={mockLocations}
+ jobSources={mockJobSources}
+ editJob={null}
+ resetEditJob={mockResetEditJob}
+ />
+ );
+ const addJobButton = screen.getByTestId("add-job-btn");
+ await user.click(addJobButton);
+ });
+
+ it("should open the dialog when clicked on add job button with title 'Add Job'", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(mockUser);
+
+ const dialogTitle = screen.getByTestId("add-job-dialog-title");
+ expect(dialogTitle).toBeInTheDocument();
+ expect(dialogTitle).toHaveTextContent("Add Job");
+ });
+ it("should reflect on status and date applied when applied switch toggles", async () => {
+ const appliedSwitch = screen.getByRole("switch");
+ expect(appliedSwitch).not.toBeChecked();
+ const dateApplied = screen.getByLabelText("Date Applied");
+ expect(dateApplied).toBeDisabled();
+ await user.click(appliedSwitch); // toggle applied switch
+ expect(appliedSwitch).toBeChecked();
+ expect(dateApplied).toBeEnabled(); // date applied is enabled
+ expect(dateApplied).toHaveTextContent(format(new Date(), "PP")); // to have today's date
+ const status = screen.getByLabelText("Status");
+ expect(status).toHaveTextContent("Applied");
+ await user.click(appliedSwitch);
+ expect(status).toHaveTextContent("Draft");
+ expect(dateApplied).toBeDisabled();
+ expect(dateApplied).toHaveTextContent("Pick a date");
+ });
+ it("should open the dialog when clicked on add job button with title 'Edit Job'", () => {
+ // const menuButton = screen.getByTestId("job-actions-menu-btn");
+ // user.click(editJobButton);
+ // const dialogTitle = screen.getByTestId("add-job-dialog-title");
+ // expect(dialogTitle).toBeInTheDocument();
+ // expect(dialogTitle).toHaveTextContent("Edit Job");
+ });
+ it("should show relevant react-hook-form errors", async () => {
+ const saveBtn = screen.getByTestId("save-job-btn");
+ await user.click(saveBtn);
+ expect(screen.getByText("Job title is required.")).toBeInTheDocument();
+ expect(screen.getByText("Company name is required.")).toBeInTheDocument();
+ expect(screen.getByText("Location is required.")).toBeInTheDocument();
+ expect(screen.getByText("Source is required.")).toBeInTheDocument();
+ expect(
+ screen.getByText("Job description is required.")
+ ).toBeInTheDocument();
+ });
+ it("should close the dialog when clicked on cancel button", async () => {
+ const cancelBtn = screen.getByRole("button", { name: /cancel/i });
+ const dialog = await screen.findByRole("dialog");
+ await user.click(cancelBtn);
+ expect(dialog).not.toBeInTheDocument();
+ });
+ it("should closes the dialog and submit to save job when clicked on save button", () => {});
+ it("should load and show the job title combobox list", () => {});
+ it("should load and show the company combobox list", () => {});
+ it("should load and show the location combobox list", () => {});
+ it("should load and show the job source combobox list", () => {});
+ it("should load and show the salary range select list", () => {});
+ it("should load and show the status select list", () => {});
+});
diff --git a/__tests__/SigninForm.spec.tsx b/__tests__/SigninForm.spec.tsx
index 6e17317..31b9bcf 100644
--- a/__tests__/SigninForm.spec.tsx
+++ b/__tests__/SigninForm.spec.tsx
@@ -13,11 +13,6 @@ jest.mock("next/navigation", () => ({
useRouter: jest.fn(),
}));
-jest.mock("react-dom", () => ({
- ...jest.requireActual("react-dom"),
- useFormStatus: () => ({ pending: false }),
-}));
-
describe("SigninForm Component", () => {
const mockPush = jest.fn();
diff --git a/package-lock.json b/package-lock.json
index 4c62489..fff83b4 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -52,6 +52,7 @@
"devDependencies": {
"@testing-library/jest-dom": "^6.4.6",
"@testing-library/react": "^16.0.0",
+ "@testing-library/user-event": "^14.5.2",
"@types/bcrypt": "^5.0.2",
"@types/node": "^20",
"@types/react": "^18",
@@ -3122,6 +3123,19 @@
}
}
},
+ "node_modules/@testing-library/user-event": {
+ "version": "14.5.2",
+ "resolved": "https://registry.npmjs.org/@testing-library/user-event/-/user-event-14.5.2.tgz",
+ "integrity": "sha512-YAh82Wh4TIrxYLmfGcixwD18oIjyC1pFQC2Y01F2lzV2HTMiYrI0nze0FD0ocB//CKS/7jIUgae+adPqxK5yCQ==",
+ "dev": true,
+ "engines": {
+ "node": ">=12",
+ "npm": ">=6"
+ },
+ "peerDependencies": {
+ "@testing-library/dom": ">=7.21.4"
+ }
+ },
"node_modules/@tiptap/core": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/@tiptap/core/-/core-2.4.0.tgz",
diff --git a/package.json b/package.json
index 1a62483..9b26c8f 100644
--- a/package.json
+++ b/package.json
@@ -56,6 +56,7 @@
"devDependencies": {
"@testing-library/jest-dom": "^6.4.6",
"@testing-library/react": "^16.0.0",
+ "@testing-library/user-event": "^14.5.2",
"@types/bcrypt": "^5.0.2",
"@types/node": "^20",
"@types/react": "^18",
diff --git a/src/actions/auth.actions.ts b/src/actions/auth.actions.ts
index 870ef46..33e0f32 100644
--- a/src/actions/auth.actions.ts
+++ b/src/actions/auth.actions.ts
@@ -1,12 +1,14 @@
"use server";
import { AuthError } from "next-auth";
import { signIn } from "../auth";
+import { delay } from "@/utils/delay";
export async function authenticate(
prevState: string | undefined,
formData: FormData
) {
try {
+ delay(1000);
await signIn("credentials", formData);
} catch (error) {
if (error instanceof AuthError) {
diff --git a/src/components/auth/SigninForm.tsx b/src/components/auth/SigninForm.tsx
index c3f546d..379ace2 100644
--- a/src/components/auth/SigninForm.tsx
+++ b/src/components/auth/SigninForm.tsx
@@ -2,7 +2,6 @@
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { z } from "zod";
-import { useFormStatus } from "react-dom";
import { authenticate } from "@/actions/auth.actions";
import {
Form,
@@ -14,11 +13,14 @@ import {
} from "@/components/ui/form";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
-import { useState } from "react";
+import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { SigninFormSchema } from "@/models/signinForm.schema";
+import Loading from "../Loading";
function SigninForm() {
+ const [isPending, startTransition] = useTransition();
+
const form = useForm<z.infer<typeof SigninFormSchema>>({
resolver: zodResolver(SigninFormSchema),
mode: "onChange",
@@ -27,18 +29,18 @@ function SigninForm() {
const [errorMessage, setError] = useState("");
const router = useRouter();
- const { pending } = useFormStatus();
-
- const onSubmit = async (data: z.infer<typeof SigninFormSchema>) => {
- const formData = new FormData();
- formData.set("email", data.email);
- formData.set("password", data.password);
- const errorResponse = await authenticate("", formData);
- if (!!errorResponse) {
- setError(errorResponse);
- } else {
- router.push("/dashboard");
- }
+ const onSubmit = (data: z.infer<typeof SigninFormSchema>) => {
+ startTransition(async () => {
+ const formData = new FormData();
+ formData.set("email", data.email);
+ formData.set("password", data.password);
+ const errorResponse = await authenticate("", formData);
+ if (!!errorResponse) {
+ setError(errorResponse);
+ } else {
+ router.push("/dashboard");
+ }
+ });
};
return (
@@ -90,8 +92,8 @@ function SigninForm() {
{/* </div> */}
{/* <Input id="password" type="password" required /> */}
</div>
- <Button type="submit" aria-disabled={pending} className="w-full">
- Login
+ <Button type="submit" disabled={isPending} className="w-full">
+ {isPending ? <Loading /> : "Login"}
</Button>
<div
className="flex h-8 items-end space-x-1"
diff --git a/src/components/myjobs/AddJob.tsx b/src/components/myjobs/AddJob.tsx
index a1c6641..88d4d72 100644
--- a/src/components/myjobs/AddJob.tsx
+++ b/src/components/myjobs/AddJob.tsx
@@ -50,7 +50,6 @@ type AddJobProps = {
jobTitles: JobTitle[];
locations: JobLocation[];
jobSources: JobSource[];
- reloadJobs: () => void;
editJob?: JobResponse | null;
resetEditJob: () => void;
};
@@ -61,7 +60,6 @@ export function AddJob({
jobTitles,
locations,
jobSources,
- reloadJobs,
editJob,
resetEditJob,
}: AddJobProps) {
@@ -113,7 +111,6 @@ export function AddJob({
: await addJob(data);
reset();
setDialogOpen(false);
- // reloadJobs();
if (!success) {
toast({
variant: "destructive",
@@ -153,18 +150,24 @@ export function AddJob({
return (
<>
- <Button size="sm" className="h-8 gap-1" onClick={addJobForm}>
+ <Button
+ size="sm"
+ className="h-8 gap-1"
+ onClick={addJobForm}
+ data-testid="add-job-btn"
+ >
<PlusCircle className="h-3.5 w-3.5" />
<span className="sr-only sm:not-sr-only sm:whitespace-nowrap">
Add Job
</span>
</Button>
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
- {/* <DialogTrigger asChild></DialogTrigger> */}
<DialogOverlay>
<DialogContent className="h-full xl:h-[85vh] lg:h-[95vh] lg:max-w-screen-lg lg:max-h-screen overflow-y-scroll">
<DialogHeader>
- <DialogTitle>{pageTitle}</DialogTitle>
+ <DialogTitle data-testid="add-job-dialog-title">
+ {pageTitle}
+ </DialogTitle>
</DialogHeader>
<Form {...form}>
<form
@@ -300,20 +303,27 @@ export function AddJob({
</div>
{/* Applied */}
- <div className="flex items-center">
+ <div
+ className="flex items-center"
+ data-testid="switch-container"
+ >
<FormField
control={form.control}
name="applied"
render={({ field }) => (
<FormItem className="flex flex-row">
<Switch
+ id="applied-switch"
checked={field.value}
onCheckedChange={(a) => {
field.onChange(a);
jobAppliedChange(a);
}}
/>
- <FormLabel className="flex items-center ml-4 mb-2">
+ <FormLabel
+ htmlFor="applied-switch"
+ className="flex items-center ml-4 mb-2"
+ >
{field.value ? "Applied" : "Not Applied"}
</FormLabel>
@@ -431,7 +441,7 @@ export function AddJob({
Cancel
</Button>
</div>
- <Button type="submit">
+ <Button type="submit" data-testid="save-job-btn">
Save
{isPending ? (
<Loader className="h-4 w-4 shrink-0 spinner" />
diff --git a/src/components/myjobs/JobDetails.tsx b/src/components/myjobs/JobDetails.tsx
index 187504d..ecfedf6 100644
--- a/src/components/myjobs/JobDetails.tsx
+++ b/src/components/myjobs/JobDetails.tsx
@@ -15,6 +15,7 @@ import StarterKit from "@tiptap/starter-kit";
import { Badge } from "../ui/badge";
import { cn, formatUrl } from "@/lib/utils";
import { JobResponse } from "@/models/job.model";
+import { toast } from "../ui/use-toast";
function JobDetails({ jobId }: { jobId: string }) {
const [job, setJob] = useState<JobResponse>();
@@ -25,9 +26,16 @@ function JobDetails({ jobId }: { jobId: string }) {
});
useEffect(() => {
const getJob = async (id: string) => {
- const res = await getJobDetails(id);
- editor?.commands.setContent(res.description);
- setJob(res);
+ const { job, success, message } = await getJobDetails(id);
+ if (!success) {
+ return toast({
+ variant: "destructive",
+ title: "Error!",
+ description: message,
+ });
+ }
+ editor?.commands.setContent(job.description);
+ setJob(job);
};
getJob(jobId);
}, [jobId, editor]);
diff --git a/src/components/myjobs/JobsContainer.tsx b/src/components/myjobs/JobsContainer.tsx
index 15cfc2d..fcba318 100644
--- a/src/components/myjobs/JobsContainer.tsx
+++ b/src/components/myjobs/JobsContainer.tsx
@@ -209,7 +209,6 @@ function JobsContainer({
jobTitles={titles}
locations={locations}
jobSources={sources}
- reloadJobs={reloadJobs}
editJob={editJob}
resetEditJob={resetEditJob}
/>
diff --git a/src/components/myjobs/MyJobsTable.tsx b/src/components/myjobs/MyJobsTable.tsx
index d0a94f1..570aa40 100644
--- a/src/components/myjobs/MyJobsTable.tsx
+++ b/src/components/myjobs/MyJobsTable.tsx
@@ -160,7 +160,12 @@ function MyJobsTable({
<TableCell>
<DropdownMenu>
<DropdownMenuTrigger asChild>
- <Button aria-haspopup="true" size="icon" variant="ghost">
+ <Button
+ aria-haspopup="true"
+ size="icon"
+ variant="ghost"
+ data-testid="job-actions-menu-btn"
+ >
<MoreHorizontal className="h-4 w-4" />
<span className="sr-only">Toggle menu</span>
</Button>
diff --git a/src/models/addJobForm.schema.ts b/src/models/addJobForm.schema.ts
index ac6ced5..4d5e90e 100644
--- a/src/models/addJobForm.schema.ts
+++ b/src/models/addJobForm.schema.ts
@@ -48,9 +48,13 @@ export const AddJobFormSchema = z.object({
//
dateApplied: z.date().optional(),
salaryRange: z.string(),
- jobDescription: z.string().min(10, {
- message: "Job description must be at least 10 characters.",
- }),
+ jobDescription: z
+ .string({
+ required_error: "Job description is required.",
+ })
+ .min(10, {
+ message: "Job description must be at least 10 characters.",
+ }),
jobUrl: z.string().optional(),
applied: z.boolean().default(false),
});