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 }