Google Antigravity Directory

The #1 directory for Google Antigravity prompts, rules, workflows & MCP servers. Optimized for Gemini 3 agentic development.

Resources

PromptsMCP ServersAntigravity RulesGEMINI.md GuideBest Practices

Company

Submit PromptAntigravityAI.directory

Popular Prompts

Next.js 14 App RouterReact TypeScriptTypeScript AdvancedFastAPI GuideDocker Best Practices

Legal

Privacy PolicyTerms of ServiceContact Us
Featured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver ToolsFeatured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver Tools

© 2026 Antigravity AI Directory. All rights reserved.

The #1 directory for Google Antigravity IDE

This website is not affiliated with, endorsed by, or associated with Google LLC. "Google" and "Gemini" are trademarks of Google LLC.

Antigravity AI Directory
PromptsMCPBest PracticesUse CasesLearn
Home
Prompts
Vitest React Testing Patterns

Vitest React Testing Patterns

Build comprehensive test suites with Vitest in Google Antigravity applications including mocking, coverage, and React component testing.

vitesttestingunit-testsreact-testing-librarytypescript
by antigravity-team
⭐0Stars
.antigravity
# 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 updates

When to Use This Prompt

This vitest prompt is ideal for developers working on:

  • vitest applications requiring modern best practices and optimal performance
  • Projects that need production-ready vitest code with proper error handling
  • Teams looking to standardize their vitest development workflow
  • Developers wanting to learn industry-standard vitest patterns and techniques

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.

How to Use

  1. Copy the prompt - Click the copy button above to copy the entire prompt to your clipboard
  2. Paste into your AI assistant - Use with Claude, ChatGPT, Cursor, or any AI coding tool
  3. Customize as needed - Adjust the prompt based on your specific requirements
  4. Review the output - Always review generated code for security and correctness
💡 Pro Tip: For best results, provide context about your project structure and any specific constraints or preferences you have.

Best Practices

  • ✓ Always review generated code for security vulnerabilities before deploying
  • ✓ Test the vitest code in a development environment first
  • ✓ Customize the prompt output to match your project's coding standards
  • ✓ Keep your AI assistant's context window in mind for complex requirements
  • ✓ Version control your prompts alongside your code for reproducibility

Frequently Asked Questions

Can I use this vitest prompt commercially?

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.

Which AI assistants work best with this prompt?

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.

How do I customize this prompt for my specific needs?

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.

Related Prompts

💬 Comments

Loading comments...