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.

10.9 KB
Raw Blame
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

vi.mock("@prisma/client", () => {
  const m = {
    automationRun: {
      create: vi.fn(),
      update: vi.fn(),
      updateMany: vi.fn(),
    },
    automation: { findUnique: vi.fn(), update: vi.fn() },
    resume: { findUnique: vi.fn() },
    userSettings: { findUnique: vi.fn() },
    job: { findMany: vi.fn(), create: vi.fn() },
    jobTitle: { findUnique: vi.fn(), create: vi.fn() },
    location: { findUnique: vi.fn(), create: vi.fn() },
    company: { findUnique: vi.fn(), create: vi.fn() },
    jobSource: { findUnique: vi.fn(), create: vi.fn() },
    jobStatus: { findFirst: vi.fn(), findUnique: vi.fn(), create: vi.fn() },
    jobStage: { create: vi.fn() },
    jobStageType: {
      findUnique: vi.fn(),
      aggregate: vi.fn(),
      create: vi.fn(),
    },
  };
  return {
    PrismaClient: vi.fn(function () {
      return m;
    }),
  };
});

vi.mock("@/lib/scraper/greenhouse", () => ({
  searchGreenhouseJobs: vi.fn(),
}));

vi.mock("@/lib/scraper/lever", () => ({
  searchLeverJobs: vi.fn(),
}));

vi.mock("@/lib/api-key-resolver", () => ({
  resolveApiKey: vi.fn().mockResolvedValue(undefined),
}));

vi.mock("@/lib/ai/provider-registry.server", () => ({
  PROVIDER_VERIFIERS: { ollama: vi.fn().mockResolvedValue({ success: true }) },
}));

vi.mock("ai", () => ({ generateText: vi.fn() }));

vi.mock("@/lib/notifications/record", () => ({
  recordRunNotifications: vi.fn(),
}));

vi.mock("@/lib/ai", async (orig) => {
  const actual = await (orig() as Promise<Record<string, unknown>>);
  return { ...actual, getModel: vi.fn().mockResolvedValue({}) };
});

import { runAutomation } from "@/lib/scraper/runner";
import { searchGreenhouseJobs } from "@/lib/scraper/greenhouse";
import { searchLeverJobs } from "@/lib/scraper/lever";
import { generateText } from "ai";
import { recordRunNotifications } from "@/lib/notifications/record";
import type { Automation } from "@/models/automation.model";

function makeJob(title: string, description = "", extra = {}) {
  return {
    title,
    company: "Acme",
    location: "Remote",
    description,
    url: `https://jobs.lever.co/acme/${Math.random()}`,
    postedDate: "2026-06-01T00:00:00Z",
    ...extra,
  };
}

const leverAutomation: Automation = {
  id: "auto-lever",
  userId: "user1",
  name: "Lever",
  jobBoard: "lever",
  keywords: "",
  location: "",
  sourceConfig: JSON.stringify({
    lever: {
      companies: [{ name: "Acme", token: "acme", host: "eu" }],
      targetTitles: ["Frontend Engineer"],
      keywords: [],
      locations: [],
      strictLocation: false,
    },
  }),
  resumeId: "resume1",
  matchThreshold: 80,
  scheduleHour: 8,
  nextRunAt: null,
  lastRunAt: null,
  status: "active",
  createdAt: new Date(),
  updatedAt: new Date(),
};

describe("runAutomation (lever)", () => {
  beforeEach(() => {
    vi.clearAllMocks();

    (prisma.automationRun.create as any).mockResolvedValue({ id: "run1" });
    (prisma.automationRun.update as any).mockResolvedValue({
      id: "run1",
      automationId: "auto-lever",
    });
    (prisma.automation.findUnique as any).mockResolvedValue({ scheduleHour: 8 });
    (prisma.automation.update as any).mockResolvedValue({});
    (prisma.userSettings.findUnique as any).mockResolvedValue(null);
    (prisma.resume.findUnique as any).mockResolvedValue({
      id: "resume1",
      title: "My Resume",
      ContactInfo: null,
      ResumeSections: [],
    });
    (prisma.job.findMany as any).mockResolvedValue([]);
    (prisma.job.create as any).mockResolvedValue({});
    (prisma.jobTitle.findUnique as any).mockResolvedValue({ id: "jt" });
    (prisma.location.findUnique as any).mockResolvedValue({ id: "loc" });
    (prisma.company.findUnique as any).mockResolvedValue({ id: "co" });
    (prisma.jobSource.findUnique as any).mockResolvedValue({ id: "src" });
    (prisma.jobStatus.findFirst as any).mockResolvedValue({ id: "st" });
    // Every saved job now gets its first current stage, which resolves the
    // status-named stage type through the same Prisma mock.
    (prisma.jobStatus.findUnique as any).mockResolvedValue({
      id: "st",
      label: "New",
    });
    (prisma.jobStageType.findUnique as any).mockResolvedValue({
      id: "stage-type-new",
      label: "New",
    });
    (prisma.jobStage.create as any).mockResolvedValue({ id: "stage-1" });

    (generateText as any).mockResolvedValue({
      text: "SCORES: match=90 recommendation=strong match\n\n## Summary\nGreat fit",
    });
  });

  it("dispatches to the Lever provider (reads the lever config key), not Greenhouse", async () => {
    (searchLeverJobs as any).mockResolvedValue({
      jobs: [makeJob("Frontend Engineer", "React")],
      errors: [],
    });

    const result = await runAutomation(leverAutomation);

    expect(result.status).toBe("completed");
    expect((searchLeverJobs as any).mock.calls.length).toBe(1);
    expect((searchGreenhouseJobs as any).mock.calls.length).toBe(0);
    // The lever config's companies (with host) are passed through.
    expect((searchLeverJobs as any).mock.calls[0][0]).toEqual([
      { name: "Acme", token: "acme", host: "eu" },
    ]);
    expect(result.jobsSaved).toBe(1);
  });

  it("does not save an analyzed job scoring below the match threshold", async () => {
    (searchLeverJobs as any).mockResolvedValue({
      jobs: [makeJob("Frontend Engineer", "React")],
      errors: [],
    });
    (generateText as any).mockResolvedValue({
      text: "SCORES: match=40 recommendation=weak match\n\n## Summary\nThin fit",
    });

    const result = await runAutomation(leverAutomation);

    expect(result.status).toBe("completed");
    expect(result.jobsProcessed).toBe(1); // analyzed
    expect(result.jobsMatched).toBe(0);
    expect(result.jobsSaved).toBe(0);
    expect((prisma.job.create as any).mock.calls.length).toBe(0);
  });

  it("persists Lever's workplaceType through to the job record", async () => {
    (searchLeverJobs as any).mockResolvedValue({
      jobs: [makeJob("Frontend Engineer", "React", { workplaceType: "HYBRID" })],
      errors: [],
    });

    await runAutomation(leverAutomation);

    const createArg = (prisma.job.create as any).mock.calls[0][0];
    expect(createArg.data.workplaceType).toBe("HYBRID");
  });

  it("fails cleanly with no_companies when the lever config is empty", async () => {
    const auto = {
      ...leverAutomation,
      sourceConfig: JSON.stringify({ lever: { companies: [] } }),
    };

    const result = await runAutomation(auto);
    expect(result.status).toBe("failed");
    expect(result.errorMessage).toBe("no_companies");
    expect((searchLeverJobs as any).mock.calls.length).toBe(0);
  });

  it("strips HTML and decodes entities from the resume before matching", async () => {
    (prisma.resume.findUnique as any).mockResolvedValue({
      id: "resume1",
      title: "My Resume",
      ContactInfo: null,
      ResumeSections: [
        {
          sectionType: "experience",
          workExperiences: [
            {
              description: "<p>Sales &amp; Marketing</p>",
              startDate: new Date("2020-01-01"),
              endDate: null,
              Company: { label: "Acme" },
              jobTitle: { label: "Engineer" },
              location: { label: "Remote" },
            },
          ],
        },
      ],
    });
    (searchLeverJobs as any).mockResolvedValue({
      jobs: [makeJob("Frontend Engineer", "React")],
      errors: [],
    });

    await runAutomation(leverAutomation);

    const prompt = (generateText as any).mock.calls[0][0].prompt as string;
    expect(prompt).toContain("Sales & Marketing");
    expect(prompt).not.toContain("&amp;");
    expect(prompt).not.toContain("<p>");
  });

  it("tags a saved job with the resume skills its posting mentions", async () => {
    (prisma.resume.findUnique as any).mockResolvedValue({
      id: "resume1",
      title: "My Resume",
      ContactInfo: null,
      ResumeSections: [
        {
          sectionType: "skills",
          skills: [
            { category: null, order: 0, Tag: { id: "tag-react", label: "React" } },
            { category: null, order: 1, Tag: { id: "tag-rust", label: "Rust" } },
          ],
        },
      ],
    });
    (searchLeverJobs as any).mockResolvedValue({
      jobs: [makeJob("Frontend Engineer", "We build with React every day")],
      errors: [],
    });

    await runAutomation(leverAutomation);

    const createArg = (prisma.job.create as any).mock.calls[0][0];
    expect(createArg.data.tags).toEqual({ connect: [{ id: "tag-react" }] });
  });

  it("omits tags when the resume has no skills section", async () => {
    (searchLeverJobs as any).mockResolvedValue({
      jobs: [makeJob("Frontend Engineer", "We build with React every day")],
      errors: [],
    });

    await runAutomation(leverAutomation);

    const createArg = (prisma.job.create as any).mock.calls[0][0];
    expect("tags" in createArg.data).toBe(false);
  });

  describe("board failures", () => {
    const twoBoards: Automation = {
      ...leverAutomation,
      sourceConfig: JSON.stringify({
        lever: {
          companies: [
            { name: "Acme", token: "acme" },
            { name: "Globex", token: "globex" },
          ],
          targetTitles: ["Frontend Engineer"],
          keywords: [],
          locations: [],
          strictLocation: false,
        },
      }),
    };

    it("fails the run when every board errored", async () => {
      (searchLeverJobs as any).mockResolvedValue({
        jobs: [],
        errors: [
          { token: "acme", reason: "Board 'acme' returned 404" },
          { token: "globex", reason: "Board 'globex' timed out" },
        ],
      });

      const result = await runAutomation(twoBoards);

      expect(result.status).toBe("failed");
      expect(result.errorMessage).toBe("All 2 boards unreachable");
      const finalizeData = (recordRunNotifications as any).mock.calls[0][1];
      expect(finalizeData.boardErrors).toEqual([
        { token: "acme", name: "Acme", reason: "Board 'acme' returned 404" },
        { token: "globex", name: "Globex", reason: "Board 'globex' timed out" },
      ]);
    });

    it("completes with errors when only some boards errored", async () => {
      (searchLeverJobs as any).mockResolvedValue({
        jobs: [],
        errors: [{ token: "acme", reason: "Board 'acme' returned 404" }],
      });

      const result = await runAutomation(twoBoards);

      // Takes the "nothing new" early return, which must still carry it.
      expect(result.status).toBe("completed_with_errors");
      expect(result.errorMessage).toBe("1 of 2 boards unreachable");
      const finalizeData = (recordRunNotifications as any).mock.calls[0][1];
      expect(finalizeData.boardErrors).toHaveLength(1);
    });

    it("stays completed when no board errored", async () => {
      (searchLeverJobs as any).mockResolvedValue({ jobs: [], errors: [] });
      const result = await runAutomation(twoBoards);
      expect(result.status).toBe("completed");
      expect(result.errorMessage).toBeUndefined();
    });
  });
});