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
MSW API Mocking Patterns

MSW API Mocking Patterns

Master MSW API mocking patterns for Google Antigravity IDE testing and development

MSWAPI MockingTestingTypeScript
by Antigravity AI
⭐0Stars
.antigravity
# MSW API Mocking Patterns for Google Antigravity IDE

Build reliable API mocks with MSW using Google Antigravity IDE. This guide covers handler setup, network scenarios, and integration testing patterns.

## Handler Setup

```typescript
// src/mocks/handlers.ts
import { http, HttpResponse, delay } from "msw";
import { db } from "./db";

export const handlers = [
  // Users API
  http.get("/api/users", async ({ request }) => {
    const url = new URL(request.url);
    const page = parseInt(url.searchParams.get("page") || "1");
    const limit = parseInt(url.searchParams.get("limit") || "20");
    const search = url.searchParams.get("q");

    await delay(100);

    let users = db.user.getAll();

    if (search) {
      users = users.filter((u) =>
        u.name.toLowerCase().includes(search.toLowerCase()) ||
        u.email.toLowerCase().includes(search.toLowerCase())
      );
    }

    const start = (page - 1) * limit;
    const paginatedUsers = users.slice(start, start + limit);

    return HttpResponse.json({
      users: paginatedUsers,
      total: users.length,
      page,
      limit,
    });
  }),

  http.get("/api/users/:id", async ({ params }) => {
    await delay(50);

    const user = db.user.findFirst({ where: { id: { equals: params.id as string } } });

    if (!user) {
      return HttpResponse.json({ message: "User not found" }, { status: 404 });
    }

    return HttpResponse.json(user);
  }),

  http.post("/api/users", async ({ request }) => {
    const body = await request.json();
    await delay(100);

    const user = db.user.create({
      ...body,
      id: crypto.randomUUID(),
      createdAt: new Date().toISOString(),
    });

    return HttpResponse.json(user, { status: 201 });
  }),

  http.patch("/api/users/:id", async ({ params, request }) => {
    const body = await request.json();
    await delay(100);

    const user = db.user.update({
      where: { id: { equals: params.id as string } },
      data: body,
    });

    if (!user) {
      return HttpResponse.json({ message: "User not found" }, { status: 404 });
    }

    return HttpResponse.json(user);
  }),

  http.delete("/api/users/:id", async ({ params }) => {
    await delay(50);

    db.user.delete({ where: { id: { equals: params.id as string } } });

    return new HttpResponse(null, { status: 204 });
  }),
];
```

## Mock Database

```typescript
// src/mocks/db.ts
import { factory, primaryKey } from "@mswjs/data";
import { faker } from "@faker-js/faker";

export const db = factory({
  user: {
    id: primaryKey(faker.string.uuid),
    email: () => faker.internet.email(),
    name: () => faker.person.fullName(),
    role: () => faker.helpers.arrayElement(["user", "admin"]),
    avatar: () => faker.image.avatar(),
    createdAt: () => faker.date.past().toISOString(),
  },
  post: {
    id: primaryKey(faker.string.uuid),
    title: () => faker.lorem.sentence(),
    content: () => faker.lorem.paragraphs(3),
    authorId: () => faker.string.uuid(),
    published: () => faker.datatype.boolean(),
    createdAt: () => faker.date.past().toISOString(),
  },
});

// Seed initial data
for (let i = 0; i < 50; i++) {
  db.user.create();
}

for (let i = 0; i < 100; i++) {
  db.post.create();
}
```

## Browser Setup

```typescript
// src/mocks/browser.ts
import { setupWorker } from "msw/browser";
import { handlers } from "./handlers";

export const worker = setupWorker(...handlers);

// src/app/providers.tsx
"use client";

import { useEffect, useState } from "react";

export function MockProvider({ children }: { children: React.ReactNode }) {
  const [ready, setReady] = useState(false);

  useEffect(() => {
    if (process.env.NODE_ENV === "development" && process.env.NEXT_PUBLIC_ENABLE_MOCKS === "true") {
      import("@/mocks/browser").then(({ worker }) => {
        worker.start({ onUnhandledRequest: "bypass" }).then(() => setReady(true));
      });
    } else {
      setReady(true);
    }
  }, []);

  if (!ready) return null;

  return children;
}
```

## Testing Integration

```typescript
// src/mocks/server.ts
import { setupServer } from "msw/node";
import { handlers } from "./handlers";

export const server = setupServer(...handlers);

// vitest.setup.ts
import { beforeAll, afterEach, afterAll } from "vitest";
import { server } from "@/mocks/server";

beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
```

## Best Practices for Google Antigravity IDE

When using MSW with Google Antigravity, create realistic mock data with Faker. Use database factory for stateful mocks. Test error scenarios. Share handlers between browser and tests. Let Gemini 3 generate handlers from OpenAPI specs.

Google Antigravity excels at creating comprehensive API mocks with MSW.

When to Use This Prompt

This MSW prompt is ideal for developers working on:

  • MSW applications requiring modern best practices and optimal performance
  • Projects that need production-ready MSW code with proper error handling
  • Teams looking to standardize their msw development workflow
  • Developers wanting to learn industry-standard MSW 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 msw 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 MSW 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 MSW 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 MSW projects, consider mentioning your framework version, coding style, and any specific libraries you're using.

Related Prompts

💬 Comments

Loading comments...