gpt4 book ai didi

reactjs - 如何使用 msw 有条件地模拟错误响应

转载 作者:行者123 更新时间:2023-12-05 01:07:38 29 4
gpt4 key购买 nike

我正在处理的 UI 会根据收到的响应以不同的方式呈现。我想在收到 4xx5xx 响应时测试 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 响应,如果收到 4xx5xx 响应,则无法测试 UI,除非我更改手动处理,很累。

如何测试 4xx5xx 响应的测试?

最佳答案

使用搜索参数来控制 get 请求的响应。

req.body 中传递一个变量来控制 post 请求的响应是否成功。

Conditional response

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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com