获取模拟 Service Worker 的请求正文和反应测试库

Pat*_*emi 4 reactjs msw

所以我正在为我的一个 React 项目编写测试,我只是决定使用模拟服务工作者来模拟我的 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
        })
      );
    }
  })
);
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?有更好的方法吗?

ket*_*ito 8

编辑:城市固体废弃物2.0

\n

自MSW 2.0发布以来,您使用请求/响应主体的方式与使用 Fetch API 的方式相同。

\n
import { http, HttpResponse } from \'msw\'\nimport { setupServer } from \'msw/node\'\n\nsetupServer(\n  http.post(\'/endpoint\', async ({ request }) => {\n    const data = await request.formData()\n    const email = data.get(\'email\')\n  \n    if (email !== \'test@example.com\') {\n      return HttpResponse.json({ success: false }, { status: 401 })\n    }\n\n    return HttpResponse.json({ success: true })\n  })\n)\n
Run Code Online (Sandbox Code Playgroud)\n
\n

在此示例中,我将请求正文读取为FormData. 您也可以将其读作.json(),.text()等。\xe2\x80\x94 这些是常规的Request实例方法。

\n
\n

了解有关新版本 MSW以及如何从 1.x 迁移到 2.x 的更多信息。

\n

城市固体废弃物1.0

\n

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

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

ctx.status(401)请注意该调用是如何在函数调用内部进行的res()。调用ctx[abc]外部的任何方法都res不会产生任何效果,因为它们依赖于被包装在res.

\n
\n

  • `req.body()` 现已弃用,如果您的正文有 JSON 数据,您可以使用 `req.json()` ([docs](https://mswjs.io/docs/api/request)) (9认同)