0
0
Remixframework~5 mins

Mocking data in tests in Remix

Choose your learning style9 modes available
Introduction

Mocking data helps you test your Remix app without needing real servers or databases. It makes tests faster and more reliable.

When you want to test a Remix loader without calling a real API.
When you need to simulate user data in your tests.
When your test should not depend on external services.
When you want to check how your component behaves with different data.
When you want to isolate parts of your app to find bugs easily.
Syntax
Remix
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.

Examples
This mocks fetch to always return a user named Alice.
Remix
import { vi } from 'vitest';

const mockData = { name: 'Alice' };

vi.stubGlobal('fetch', vi.fn(() =>
  Promise.resolve({ json: () => Promise.resolve(mockData) })
));
This mocks fetch to simulate a network error.
Remix
import { vi } from 'vitest';

const mockError = new Error('Network error');

vi.stubGlobal('fetch', vi.fn(() =>
  Promise.reject(mockError)
));
Sample Program

This test mocks the global fetch function so the Remix loader returns the mocked data instead of calling a real API.

Remix
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);
  });
});
OutputSuccess
Important Notes

Always reset mocks after tests to avoid side effects.

Mock only what you need to keep tests simple and clear.

Summary

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.