How to Use Vitest with Remix: Setup and Example
To use
vitest with remix, install vitest and configure it in your Remix project by adding a vitest.config.ts file. Then write tests in your app directory and run them with the vitest command.Syntax
Here is the basic setup syntax for using vitest in a Remix project:
npm install -D vitest @testing-library/react @testing-library/jest-dominstalls Vitest and testing helpers.- Create a
vitest.config.tsfile to configure Vitest for Remix. - Write test files with
testordescribeblocks inside yourappfolder. - Run tests using the
vitestCLI command.
typescript
import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { environment: 'jsdom', globals: true, setupFiles: './vitest.setup.ts', }, });
Example
This example shows a simple React component test in Remix using Vitest and Testing Library.
typescript
import { render, screen } from '@testing-library/react'; import { test, expect } from 'vitest'; function Greeting({ name }: { name: string }) { return <h1>Hello, {name}!</h1>; } test('renders greeting with name', () => { render(<Greeting name="Remix" />); expect(screen.getByText('Hello, Remix!')).toBeDefined(); });
Output
PASS Greeting renders greeting with name
Common Pitfalls
Common mistakes when using Vitest with Remix include:
- Not setting
environment: 'jsdom'invitest.config.ts, causing DOM APIs to fail. - Forgetting to install
@testing-library/reactand@testing-library/jest-domfor React component testing. - Placing test files outside the
appdirectory or not naming them with.test.tsxor.spec.tsx.
Example of a wrong config missing jsdom environment:
typescript
import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { globals: true, // Missing environment: 'jsdom' causes errors when testing React components }, });
Quick Reference
| Step | Command / File | Purpose |
|---|---|---|
| 1 | npm install -D vitest @testing-library/react @testing-library/jest-dom | Install Vitest and React testing helpers |
| 2 | vitest.config.ts | Configure Vitest with jsdom environment and globals |
| 3 | vitest.setup.ts | Optional setup file for global test setup |
| 4 | app/**/*.test.tsx | Write test files inside Remix app folder |
| 5 | npx vitest | Run tests with Vitest CLI |
Key Takeaways
Install Vitest and React testing libraries to test Remix components.
Configure Vitest with jsdom environment for DOM support.
Write tests inside the Remix app folder with proper naming.
Run tests using the Vitest CLI command.
Avoid missing environment config to prevent test failures.