【问题标题】:How to conditionally mock error responses with msw如何使用 msw 有条件地模拟错误响应
【发布时间】:2021-07-17 03:48:16
【问题描述】:

我正在处理的 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 响应的测试?

【问题讨论】:

  • 情况是什么样的?
  • 我试图弄清楚如何使用相同的 url 返回不同的响应,例如成功的响应 rest.get('/items/', (_req, res, ctx) => res(ctx.status(200), ctx.json(items))) 和不成功的响应 rest.get('/items/', (_req, res, ctx) => res.networkError('Network error')) 那么我如何选择成功或不成功的响应时测试请求依赖组件。

标签: reactjs testing jestjs msw


【解决方案1】:

使用搜索参数来控制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(200),
        ctx.json({
          errorMessage: 'Network error',
        }),
      )
    }

    // successful response
    return res(ctx.status(200), ctx.json(items));
  }),
)

【讨论】:

  • 由于无法在 get 请求中传递正文,它将如何处理 get 请求。
  • @TimothyOliver 更新了答案。
猜你喜欢
  • 2022-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-22
相关资源
最近更新 更多