Introduction
When developing with React and Supabase, it can be dangerous to run production transitions or database access in tests.
Mocks (fake functions) are often used to address this issue.
Here, we've compiled a list of standard mocking patterns that can be used with React Router, Supabase, and fetch.
1. React Router (Mock useNavigate)
// Fake navigate function
const mockNavigate = jest.fn();
jest.mock("react-router-dom", () => ({
...jest.requireActual("react-router-dom"),
useNavigate: () => mockNavigate,
}));
// Test example
fireEvent.click(screen.getByText("Back"));
expect(mockNavigate).toHaveBeenCalledWith("/");
2. Superbase (users table)
jest.mock("../../supabase", () => ({
supabase: {
from: jest.fn(() => ({
select: jest.fn().mockReturnThis(),
eq: jest.fn().mockReturnThis(),
single: jest.fn().mockResolvedValue({
data: { id: "alice", name: "Alice" },
error: null,
}),
})),
},
}));
// supabase.from("users").select().eq("id","alice").single()
// → Always returns Alice
3. Fetch API
global.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve({ message: "Hello World" }),
})
) as jest.Mock;
// Test example
const res = await fetch("/api/hello");
expect(await res.json()).toEqual({ message: "Hello World" });
4. Sharing (mocks folder)
// __mocks__/supabase.ts
export const supabase = {
from: jest.fn(() => ({
select: jest.fn().mockReturnThis(),
eq: jest.fn().mockReturnThis(),
single: jest.fn().mockResolvedValue({
data: { id: "alice", name: "Alice" },
error: null,
}),
})),
};
// Test side
jest.mock("../../supabase");
Summary
Router → Mock page transitions
Supabase → Mock database access
fetch → Mock API requests
Sharing → Consolidate in mocks
Top comments (0)