4

Here's the Express Route code that is working fine in back and frontend.

// Edit/update by vessel_type by_id - Working

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);
      }
    }
  );
});

And here's my API test code in React front-end with nock

  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();
      });
  });

The console logging of the error from the test gives the following in Terminal

    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)

However my PUT routes (http://localhost:3000/api/vesseltype/5c62cc8f1774b626cd7fdbe6) is matching perfectly between nock and axios.

I have gone through these github issues and SO questions here, here, and here but those solutions did not help me.

Rohan_Paul
  • 1,207
  • 21
  • 30

1 Answers1

0

Apparently your framework/lib calls OPTIONS request before calling the PUT. It's related with CORS. Described here

You may try nock-ing OPTIONS.

juzeff
  • 26
  • 2