使用 Nock 进行 React API 测试失败,并显示“错误:Nock:与请求不匹配”

Roh*_*aul 5 node.js express reactjs nock

这是在后端和前端运行良好的 Express Route 代码。

// 按 Vessel_type by_id 编辑/更新 - 工作

router.put("/:id", (req, res, next) => {
  Vessel_Type.findByIdAndUpdate(
    req.params.id,
    req.body,

    { new: true },
    (err, updatedRecord) => {
      if (err) {
        console.error(err);
        return next(err);
      } else {
        res.status(200).send(updatedRecord);
      }
    }
  );
});
Run Code Online (Sandbox Code Playgroud)

这是我在 React 前端使用nock进行 API 测试的代码

  it("API test-3 - PUT (/api/vesseltype/id)", done => {
    nock(host)
      .defaultReplyHeaders({
        "access-control-allow-origin": "*",
        "Content-Type": "application/json"
      })
      .persist()
      .log(console.log)
      .put("/api/vesseltype/5c62cc8f1774b626cd7fdbe6", {
        vesseltype: "Super Large Cargo Ship-45"
      })
      .delayBody(1000)
      .reply(200, "PUT/EDIT data with reqheaders");

    axios
      .put("http://localhost:3000/api/vesseltype/5c62cc8f1774b626cd7fdbe6", {
        vesseltype: "Super Large Cargo Ship-45"
      })
      .then(response => {
        expect(response.data).toBe("PUT/EDIT data with reqheaders");
        expect(typeof response.data).toBe("string");
        done();
      });
  });
Run Code Online (Sandbox Code Playgroud)

测试错误的控制台记录在终端中给出以下内容

    console.log node_modules/nock/lib/interceptor.js:332
    matching http://localhost:3000/api/vesseltype/5c62cc8f1774b626cd7fdbe6 to PUT http://localhost:3000/api/vesseltype/5c62cc8f1774b626cd7fdbe6: false

  console.error node_modules/jsdom/lib/jsdom/virtual-console.js:29
    Error: Error: Nock: No match for request {
      "method": "OPTIONS",
      "url": "http://localhost:3000/api/vesseltype/5c62cc8f1774b626cd7fdbe6",
      "headers": {
        "origin": "http://localhost",
        "access-control-request-method": "PUT",
        "user-agent": "Mozilla/5.0 (linux) AppleWebKit/537.36 (KHTML, like Gecko) jsdom/11.12.0",
        "host": "localhost:3000",
        "content-length": 0
      }
    }
        at Object.dispatchError (/home/paul/codes-Lap/React/Volteo/IES/IES-Rohan-WIP/client/node_modules/jsdom/lib/jsdom/living/xhr-utils.js:65:19)
        at EventEmitter.client.on.err (/home/paul/codes-Lap/React/Volteo/IES/IES-Rohan-WIP/client/node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:676:20)
        at EventEmitter.emit (events.js:202:15)
Run Code Online (Sandbox Code Playgroud)

然而,我的 PUT 路由(http://localhost:3000/api/vesseltype/5c62cc8f1774b626cd7fdbe6)在 nock 和 axios 之间完美匹配。

我已经在这里这里这里浏览了这些 github 问题和 SO 问题,但这些解决方案对我没有帮助。

小智 0

显然,您的框架/lib 在调用 PUT 之前调用 OPTIONS 请求。和CORS有关系。 此处描述

您可以尝试使用 noock-ing OPTIONS。