Skip to content

Commit f91b65a

Browse files
fix: resolve jest mock hoisting in PromptForm tests
1 parent a811cd7 commit f91b65a

1 file changed

Lines changed: 21 additions & 23 deletions

File tree

__tests__/components/PromptForm.test.tsx

Lines changed: 21 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -15,39 +15,37 @@ import { PromptForm } from "@/components/PromptForm";
1515

1616
// ── Mocks ────────────────────────────────────────────────────────────────────
1717

18-
const mockPush = jest.fn();
19-
jest.mock("next/navigation", () => ({
20-
useRouter: () => ({ push: mockPush }),
21-
}));
18+
// jest.mock() is hoisted before variable declarations, so factories must only
19+
// use jest.fn() inline — no outer variables. We then import the mocked hooks
20+
// and call mockReturnValue() to inject our named jest.fn() references.
21+
jest.mock("next/navigation", () => ({ useRouter: jest.fn() }));
22+
jest.mock("@/lib/hooks/usePrompts", () => ({ usePrompts: jest.fn() }));
23+
jest.mock("@/lib/promptData", () => ({ savePrompt: jest.fn(() => Promise.resolve()) }));
24+
jest.mock("@/components/AuthProvider", () => ({ useAuth: jest.fn() }));
25+
26+
import { useRouter } from "next/navigation";
27+
import { usePrompts } from "@/lib/hooks/usePrompts";
28+
import { savePrompt } from "@/lib/promptData";
29+
import { useAuth } from "@/components/AuthProvider";
2230

31+
const mockPush = jest.fn();
2332
const mockAddOptimistic = jest.fn();
2433
const mockRefresh = jest.fn(() => Promise.resolve());
25-
jest.mock("@/lib/hooks/usePrompts", () => ({
26-
usePrompts: () => ({
34+
const mockSavePrompt = savePrompt as jest.Mock;
35+
36+
// ── Helpers ──────────────────────────────────────────────────────────────────
37+
38+
function renderWithAuth(user: object | null = { id: "user-1", email: "test@example.com" }) {
39+
(useRouter as jest.Mock).mockReturnValue({ push: mockPush });
40+
(usePrompts as jest.Mock).mockReturnValue({
2741
addOptimistic: mockAddOptimistic,
2842
refresh: mockRefresh,
2943
prompts: [],
3044
loading: false,
3145
error: null,
3246
updateOptimistic: jest.fn(),
3347
removeOptimistic: jest.fn(),
34-
}),
35-
}));
36-
37-
const mockSavePrompt = jest.fn(() => Promise.resolve());
38-
jest.mock("@/lib/promptData", () => ({
39-
savePrompt: mockSavePrompt,
40-
}));
41-
42-
jest.mock("@/components/AuthProvider", () => ({
43-
useAuth: jest.fn(),
44-
}));
45-
46-
import { useAuth } from "@/components/AuthProvider";
47-
48-
// ── Helpers ──────────────────────────────────────────────────────────────────
49-
50-
function renderWithAuth(user: object | null = { id: "user-1", email: "test@example.com" }) {
48+
});
5149
(useAuth as jest.Mock).mockReturnValue({ user });
5250
return render(<PromptForm />);
5351
}

0 commit comments

Comments
 (0)