Sometimes, either within your test or your implementation, you want to change what is being returned from a particular handler or you want to return an error. MSW allows you to do this with server.use.
const server = setupServer(
http.get('https://example.com/book/:bookId', () => {
return json({ title: 'Lord of the Rings' })
}),
)
afterEach(() => {
// Resets all runtime request handlers added via `server.use`
server.resetHandlers()
})
beforeAll(() => {
server.listen()
})
afterAll(() => {
server.close()
})
test('handles 500 errors from the API', () => {
server.use(
// Adds a runtime request handler for posting a new book review.
http.get('https://example.com/book/:bookId', () => {
return json({ error: 'Something went wrong' }, { status: 500 })
}),
)
// Performing a "GET /book/:bookId" request
// will get the mocked response from our runtime request handler.
})
test('asserts another scenario', () => {
// Since we call `server.resetHandlers()` after each test,
// this test suite will use the default GET /book/:bookId response.
})