Build comprehensive test suites with Vitest in Google Antigravity applications including mocking, coverage, and React component testing.
# Vitest React Testing Patterns
Create robust unit test suites with Vitest in your Google Antigravity applications. This guide covers configuration, testing patterns, mocking strategies, and React component testing.
## Vitest Configuration
Set up Vitest with optimal configuration:
```typescript
// vitest.config.ts
import { defineConfig } from "vitest/config";
import react from "@vitejs/plugin-react";
import path from "path";
export default defineConfig({
plugins: [react()],
test: {
globals: true,
environment: "jsdom",
setupFiles: ["./tests/setup.ts"],
include: ["**/*.{test,spec}.{ts,tsx}"],
exclude: ["node_modules", "dist", ".next", "tests/e2e"],
coverage: {
provider: "v8",
reporter: ["text", "json", "html"],
exclude: [
"node_modules",
"tests",
"**/*.d.ts",
"**/*.config.{ts,js}",
],
thresholds: {
lines: 80,
functions: 80,
branches: 80,
statements: 80,
},
},
},
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
});
```
## Test Setup
Configure global test setup:
```typescript
// tests/setup.ts
import "@testing-library/jest-dom/vitest";
import { cleanup } from "@testing-library/react";
import { afterEach, vi } from "vitest";
// Cleanup after each test
afterEach(() => {
cleanup();
});
// Mock Next.js router
vi.mock("next/navigation", () => ({
useRouter: () => ({
push: vi.fn(),
replace: vi.fn(),
back: vi.fn(),
forward: vi.fn(),
refresh: vi.fn(),
prefetch: vi.fn(),
}),
usePathname: () => "/",
useSearchParams: () => new URLSearchParams(),
}));
```
## Unit Testing Functions
Test pure functions and utilities:
```typescript
// lib/utils.test.ts
import { describe, it, expect } from "vitest";
import { formatDate, slugify, truncate, cn } from "./utils";
describe("utils", () => {
describe("slugify", () => {
it("converts string to lowercase slug", () => {
expect(slugify("Hello World")).toBe("hello-world");
});
it("removes special characters", () => {
expect(slugify("Hello! @World#")).toBe("hello-world");
});
it("handles multiple spaces", () => {
expect(slugify("Hello World")).toBe("hello-world");
});
});
describe("truncate", () => {
it("returns original string if shorter than max", () => {
expect(truncate("Hello", 10)).toBe("Hello");
});
it("truncates and adds ellipsis", () => {
expect(truncate("Hello World", 8)).toBe("Hello...");
});
});
});
```
## React Component Testing
Test React components with Testing Library:
```typescript
// components/PromptCard.test.tsx
import { describe, it, expect, vi } from "vitest";
import { render, screen, fireEvent } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { PromptCard } from "./PromptCard";
const mockPrompt = {
id: "1",
slug: "test-prompt",
title: "Test Prompt",
description: "A test prompt description",
tags: ["react", "typescript"],
starCount: 42,
viewCount: 100,
};
describe("PromptCard", () => {
it("renders prompt information", () => {
render(<PromptCard {...mockPrompt} />);
expect(screen.getByText("Test Prompt")).toBeInTheDocument();
expect(screen.getByText("A test prompt description")).toBeInTheDocument();
expect(screen.getByText("react")).toBeInTheDocument();
});
it("displays star count", () => {
render(<PromptCard {...mockPrompt} />);
expect(screen.getByText("42")).toBeInTheDocument();
});
it("links to prompt detail page", () => {
render(<PromptCard {...mockPrompt} />);
const link = screen.getByRole("link");
expect(link).toHaveAttribute("href", "/prompts/test-prompt");
});
it("calls onStar when star button clicked", async () => {
const user = userEvent.setup();
const onStar = vi.fn();
render(<PromptCard {...mockPrompt} onStar={onStar} />);
await user.click(screen.getByRole("button", { name: /star/i }));
expect(onStar).toHaveBeenCalledWith("1");
});
});
```
## Mocking Patterns
Mock external dependencies:
```typescript
// hooks/usePrompts.test.ts
import { describe, it, expect, vi, beforeEach } from "vitest";
import { renderHook, waitFor } from "@testing-library/react";
import { usePrompts } from "./usePrompts";
import { createClient } from "@/lib/supabase/client";
vi.mock("@/lib/supabase/client", () => ({
createClient: vi.fn(),
}));
const mockSupabase = {
from: vi.fn().mockReturnThis(),
select: vi.fn().mockReturnThis(),
eq: vi.fn().mockReturnThis(),
order: vi.fn().mockResolvedValue({
data: [{ id: "1", title: "Test" }],
error: null,
}),
};
beforeEach(() => {
vi.mocked(createClient).mockReturnValue(mockSupabase as any);
});
describe("usePrompts", () => {
it("fetches prompts on mount", async () => {
const { result } = renderHook(() => usePrompts());
await waitFor(() => {
expect(result.current.data).toHaveLength(1);
});
expect(mockSupabase.from).toHaveBeenCalledWith("prompts");
});
});
```
## Best Practices
1. **Test Behavior**: Focus on testing behavior, not implementation
2. **User Events**: Use userEvent over fireEvent for realistic interactions
3. **Accessible Queries**: Prefer role and label queries over test IDs
4. **Mock Boundaries**: Mock at module boundaries, not internal functions
5. **Coverage Goals**: Aim for meaningful coverage, not 100%
6. **Async Testing**: Use waitFor for async state updatesThis vitest prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their vitest implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For vitest projects, consider mentioning your framework version, coding style, and any specific libraries you're using.