Skip to content

Instantly share code, notes, and snippets.

@claudiainbytes
Created February 11, 2026 18:44
Show Gist options
  • Select an option

  • Save claudiainbytes/325e68ed0c804242ba1892760bc98bb4 to your computer and use it in GitHub Desktop.

Select an option

Save claudiainbytes/325e68ed0c804242ba1892760bc98bb4 to your computer and use it in GitHub Desktop.
1. Testing APIs y datos asincronos: Mock Service Worker (MSW)
// mocks/handlers.ts
import { http, HttpResponse } from 'msw'
export const handlers = [
http.get('/api/products', () => {
return HttpResponse.json([
{ id: 1, name: 'Product 1', price: 100 },
{ id: 2, name: 'Product 2', price: 200 },
])
}),
http.post('/api/products', async ({ request }) => {
const product = await request.json()
return HttpResponse.json({ ...product, id: 3 }, { status: 201 })
}),
http.get('/api/products/:id', ({ params }) => {
const { id } = params
return HttpResponse.json({ id, name: `Product ${id}`, price: 100 })
}),
]
// mocks/server.ts
import { setupServer } from 'msw/node'
import { handlers } from './handlers'
export const server = setupServer(...handlers)
// test/setup.ts
import { beforeAll, afterEach, afterAll } from 'vitest'
import { server } from './mocks/server'
beforeAll(() => server.listen())
afterEach(() => server.resetHandlers())
afterAll(() => server.close())
// Test
describe('ProductList', () => {
it('carga y muestra productos', async () => {
render(<ProductList />)
expect(screen.getByText(/loading/i)).toBeInTheDocument()
const product1 = await screen.findByText('Product 1')
const product2 = screen.getByText('Product 2')
expect(product1).toBeInTheDocument()
expect(product2).toBeInTheDocument()
})
it('maneja errores de red', async () => {
server.use(
http.get('/api/products', () => {
return HttpResponse.error()
})
)
render(<ProductList />)
expect(await screen.findByText(/error loading products/i)).toBeInTheDocument()
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment