How to provoke an error and success response on the same GET endpoint #783
-
Is your feature request related to a problem? Please describe. Describe the solution you'd like Describe alternatives you've considered |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hey, @kevinmamaqi. You can use a runtime request handler to override which response is being returned for the same endpoint to test multiple states of your code. import { rest } from 'msw'
import { setupServer } from 'msw/node'
const server = setupServer(
// I recommend listing the success scenarios when declaring the server.
rest.get('/resource', (req, res, ctx) => {
return res(ctx.json({ id: 1 }))
})
)
beforeAll(() => server.listen())
afterEach(() => server.resetHandlers())
afterAll(() => server.close())
it('handles a successful response', () => {
// run your code (i.e. render components, execute functions)
// without any additions, this test case will receive a successful response
// defined above.
})
it('handles an error response', () => {
server.use(
// In this paticular test respond to the same request with a 404 response.
rest.get('/resource', (req, res, ctx) => {
return res(ctx.status(404))
})
)
// run your code here.
// within this test a "GET /resource" will receive a 404 error response
// specified above.
}) Don't forget to call .resetHandlers() after each test so that the |
Beta Was this translation helpful? Give feedback.
Hey, @kevinmamaqi. You can use a runtime request handler to override which response is being returned for the same endpoint to test multiple states of your code.