Master MSW API mocking patterns for Google Antigravity IDE testing and development
# 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.This MSW 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 msw 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 MSW projects, consider mentioning your framework version, coding style, and any specific libraries you're using.