【问题标题】:Getting request body of mock service worker and react testing library获取模拟服务工作者的请求体和反应测试库
【发布时间】:2022-01-06 23:26:55
【问题描述】:

所以我正在为我的一个反应项目编写测试,我只是决定使用模拟服务工作者来模拟我的 api 调用,我正在尝试模拟登录端点。所以我试图在我返回的地方模拟登录错误当输入与特定电子邮件不匹配时出现错误消息。给定下面的代码;

const server = setupServer(
  rest.post("https://testlogin.com/api/v1/login", (req, res, ctx) => {
    // the issue is getting the email from the request body something like the code just below
    if (req.body["email"] != "test@example.com") {
      ctx.status(401);
      return res(
        ctx.json({
          success: false
        })
      );
    }
  })
);

我该怎么做?有没有更好的方法来做到这一点?

【问题讨论】:

    标签: reactjs msw


    【解决方案1】:

    鉴于您的请求设置了Content-Type: application/json 标头,您应该能够获得req.body.email 值。如果没有 Content-Type 标头,MSW 和您的实际服务器都无法知道您尝试发送什么样的数据(如果有的话,它可以是二进制文件!)。通过提供正确的 Content-Type 标头,您可以形成正确的请求,同时让 MSW 确保 req.body 应该被解析为对象。

    // your-code.js
    fetch('https://testlogin.com/api/v1/login', {
      method: 'POST',
      headers: {
        // Adding this header is important so that "req.body"
        // is parsed into an object in your request handler.
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ login: 'admin@site.com' })
    })
    
    // your-handlers.js
    rest.post('https://testlogin.com/api/v1/login', (req, res, ctx) => {
      const { login } = req.body
    
      if (login !== 'test@example.com') {
        return res(ctx.status(401), ctx.json({ success: false }))
      }
    
      return res(ctx.json({ success: true }))
    })
    

    注意ctx.status(401) 调用是如何res() 函数调用中的。在res 之外调用任何ctx[abc] 方法都不会产生任何效果,因为它们依赖于包裹在res 中。

    【讨论】:

      猜你喜欢
      • 2022-11-11
      • 2021-04-28
      • 2019-11-29
      • 2015-08-27
      • 2021-08-18
      • 2019-02-24
      • 2020-09-12
      • 2020-02-23
      • 2017-01-31
      相关资源
      最近更新 更多