Introduction
Mocking data helps you test your Remix app without needing real servers or databases. It makes tests faster and more reliable.
Mocking data helps you test your Remix app without needing real servers or databases. It makes tests faster and more reliable.
import { vi } from 'vitest'; // Mock a fetch call vi.stubGlobal('fetch', vi.fn(() => Promise.resolve({ json: () => Promise.resolve(mockData) }) ));
Use vi.stubGlobal to replace global functions like fetch.
Return a Promise that resolves to the mocked data to mimic real fetch behavior.
fetch to always return a user named Alice.import { vi } from 'vitest'; const mockData = { name: 'Alice' }; vi.stubGlobal('fetch', vi.fn(() => Promise.resolve({ json: () => Promise.resolve(mockData) }) ));
fetch to simulate a network error.import { vi } from 'vitest'; const mockError = new Error('Network error'); vi.stubGlobal('fetch', vi.fn(() => Promise.reject(mockError) ));
This test mocks the global fetch function so the Remix loader returns the mocked data instead of calling a real API.
import { vi, describe, it, expect } from 'vitest'; import { loader } from '~/routes/example'; const mockData = { message: 'Hello from mock!' }; vi.stubGlobal('fetch', vi.fn(() => Promise.resolve({ json: () => Promise.resolve(mockData) }) )); describe('loader test with mocked fetch', () => { it('returns mocked data', async () => { const response = await loader(); expect(response).toEqual(mockData); }); });
Always reset mocks after tests to avoid side effects.
Mock only what you need to keep tests simple and clear.
Mocking replaces real data calls with fake data for testing.
Use vi.stubGlobal in Remix tests to mock fetch.
Mocking makes tests faster and more reliable.
import { rest } from 'msw';
import { setupServer } from 'msw/node';
const server = setupServer(
rest.get('/api/greet', (req, res, ctx) => {
return res(ctx.json({ message: 'Hello' }));
})
);
beforeAll(() => server.listen());
afterAll(() => server.close());
// Test function
async function fetchGreeting() {
const response = await fetch('/api/greet');
const data = await response.json();
return data.message;
}
fetchGreeting().then(console.log);Pass the test and this pattern moves unknown