Search code examples
expresssupertest

Jest / Supertest Error - Right-hand side of 'instanceof' is not callable


When using supertest like so,

import app from "../../src/app";
import request from "supertest";

describe("GET / - a simple api endpoint", () => {
  it("Hello API Request", () => {
    const result = request(app)
    .get("/api/location/5eda6d195dd81b21a056bedb")
    .then((res) => {
      console.log(res);
    })
    // expect(result.text).toEqual("hello");
    // expect(result.status).toEqual(200);

  });
});

Im getting "Right-hand side of 'instanceof' is not callable".

 at Response.toError (node_modules/superagent/lib/node/response.js:94:15)
      at ResponseBase._setStatusProperties (node_modules/superagent/lib/response-base.js:123:16)
      at new Response (node_modules/superagent/lib/node/response.js:41:8)
      at Test.Request._emitResponse (node_modules/superagent/lib/node/index.js:752:20)
      at node_modules/superagent/lib/node/index.js:916:38
      at IncomingMessage.<anonymous> (node_modules/superagent/lib/node/parsers/json.js:19:7)
      at processTicksAndRejections (internal/process/task_queues.js:84:21) {
          status: 500,
          text: `"Right-hand side of 'instanceof' is not callable"`,
          method: 'GET',
          path: '/api/location/5eda6d195dd81b21a056bedb'

This is just with supertest, the API works when using Postman.

Rest of the code for this call,

router.get(
  "/location/:id",
  (req, res) => {
    locationController.getLocation(req, res);
  }
);


const getLocation = async (req: Request, res: Response): Promise<void> => {
  const { id } = req.params;
  const location = await data.readRecord(id, Location);
  res.status(location.code).json(location.data);
};


const readRecord = async (id: string, model: IModel): Promise<Response> => {
  try {
    const response = await model.findById(id);
    if (response == null) return { code: 404, data: `ID ${id} Not Found` };
    return { code: 200, data: response };
  } catch (error) {
    return errorHandler(error);
  }
};

Is there a configuration im missing for supertest and typescript?


Solution

  • This approach worked,

    import request = require("supertest");
    import app from "../../src/app";
    
    describe("GET/ api/location/id", () => {
      it("should connect retrieve record and retrieve a code 200 and json response", async () => {
        const res = await request(app)
          .get(`/api/location/${id}`)
    
        expect(res.status).toBe(200);
        expect(res.body._id).toBe(`${id}`);
      });
    });