我正在处理的 UI 会根据收到的响应以不同的方式呈现。我想在收到 4xx
和 5xx
响应时测试 UI。
我的 api 处理程序看起来像:
import { rest } from 'msw';
import { items } from './apiValues';
export const handlers = [
rest.get('/items/', (_req, res, ctx) => res(ctx.status(200), ctx.json(items))),
];
这将始终返回 2xx
响应,如果收到 4xx
或 5xx
响应,则无法测试 UI,除非我更改手动处理,很累。
如何测试 4xx
和 5xx
响应的测试?
最佳答案
使用搜索参数来控制 get
请求的响应。
在 req.body
中传递一个变量来控制 post
请求的响应是否成功。
import { setupWorker, rest } from 'msw';
const worker = setupWorker(
rest.get('/items/', (req, res, ctx) => {
const error = req.url.searchParams.get('error')
// error response
if(error === 'network') {
return res(
ctx.status(400),
ctx.json({
errorMessage: 'Network error',
}),
)
}
// successful response
return res(ctx.status(200), ctx.json(items));
}),
)
关于reactjs - 如何使用 msw 有条件地模拟错误响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67221429/