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

时间:2019-02-26 05:13:59

标签: node.js reactjs express 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);
      }
    }
  );
});

这是我在nock

的React前端中的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();
      });
  });

控制台从测试中记录错误,在终端中提供以下内容

    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)

但是我的PUT路线(http://localhost:3000/api/vesseltype/5c62cc8f1774b626cd7fdbe6)在nock和axios之间完全匹配。

我经历了这些github问题以及诸如hereherehere之类的问题,但是这些解决方案对我没有帮助。

1 个答案:

答案 0 :(得分:0)

显然,您的框架/库在调用PUT之前先调用OPTIONS请求。 与CORS有关。 Described here

您可以尝试提示选项。