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

标签 reactjs testing jestjs msw

我正在处理的 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/

相关文章:

reactjs - Jest : TypeError: Cannot read property of undefined

node.js - Jest 提示错误……我告诉 Jest 要期待

javascript - react native : How to reference current route in Navigator's navigationBar={}?

ruby - Cucumber hooks可以区分标签吗

testing - TestNG - 是否可以将 AnnotationTransformer 与 dataProvider 一起使用?

linux - 用于在 Linux 上进行测试的 Web 服务器

javascript - 在 Jest 测试中使用expect.assertions(x) 与使用fail()

javascript - 如何停止在 textInput React Native 中输入空格?

reactjs - 我应该在哪个端口上运行 GraphQL 服务器?

css - 我如何在 react 中使用这种风格...... "class[attribute] "[Edited v.2]