useRescoreJob to reduce duplication

This commit is contained in:
DaKheera47
2026-01-25 12:06:14 +00:00
parent f491f4634e
commit 85976caf9c
4 changed files with 73 additions and 33 deletions
@@ -0,0 +1,38 @@
import { act, renderHook } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { useRescoreJob } from "./useRescoreJob";
import * as api from "../api";
import { toast } from "sonner";
vi.mock("../api", () => ({
rescoreJob: vi.fn(),
}));
vi.mock("sonner", () => ({
toast: {
success: vi.fn(),
error: vi.fn(),
},
}));
describe("useRescoreJob", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("rescoring updates the job and shows a toast", async () => {
const onJobUpdated = vi.fn().mockResolvedValue(undefined);
vi.mocked(api.rescoreJob).mockResolvedValue({} as any);
const { result } = renderHook(() => useRescoreJob(onJobUpdated));
await act(async () => {
await result.current.rescoreJob("job-1");
});
expect(api.rescoreJob).toHaveBeenCalledWith("job-1");
expect(onJobUpdated).toHaveBeenCalled();
expect(toast.success).toHaveBeenCalledWith("Match recalculated");
});
});
@@ -0,0 +1,29 @@
import { useCallback, useState } from "react";
import { toast } from "sonner";
import * as api from "../api";
export function useRescoreJob(onJobUpdated: () => void | Promise<void>) {
const [isRescoring, setIsRescoring] = useState(false);
const rescoreJob = useCallback(
async (jobId?: string | null) => {
if (!jobId) return;
try {
setIsRescoring(true);
await api.rescoreJob(jobId);
toast.success("Match recalculated");
await onJobUpdated();
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to recalculate match";
toast.error(message);
} finally {
setIsRescoring(false);
}
},
[onJobUpdated],
);
return { isRescoring, rescoreJob };
}