DEV Community

Kazutora Hattori
Kazutora Hattori

Posted on

[Introduction to Jest Mocks] A collection of templates for testing React Router / Supabase / fetch

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("/");
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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" });
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode

Summary

Router → Mock page transitions

Supabase → Mock database access

fetch → Mock API requests

Sharing → Consolidate in mocks

Top comments (0)