- Introduction
- Getting started
- Philosophy
- Comparison
- Limitations
- Debugging runbook
- FAQ
- Basics
- Concepts
- Network behavior
- Integrations
- API
- CLI
- Best practices
- Recipes
- Cookies
- Query parameters
- Response patching
- Polling
- Streaming
- Network errors
- File uploads
- Responding with binary
- Custom worker script location
- Global response delay
- GraphQL query batching
- Higher-order resolver
- Keeping mocks in sync
- Merging Service Workers
- Mock GraphQL schema
- Using CDN
- Using custom "homepage" property
- Using local HTTPS
Polling
Yield different responses on subsequent requests.
You can use generator functions in JavaScript to yield different responses on each subsequent request to an endpoint. This is particularly handy to describe HTTP polling.
import { http, HttpResponse, delay } from 'msw'
export const handlers = [
http.get('/weather/:city', async function* () {
const degree = 25
// Add random server-side latency to emulate
// a real-world server.
await delay()
while (degree < 27) {
degree++
yield HttpResponse.json({ degree: degree })
}
return HttpResponse.json({ degree: degree })
}),
]
The example above will respond with incrementing temperature degree until it reaches 28 degrees.
GET /weather/london // { "degree": 26 }
GET /weather/london // { "degree": 27 }
GET /weather/london // { "degree": 28 }
// All subsequent requests will respond
// with the latest returned response.
GET /weather/london // { "degree": 28 }