开玩笑/超级测试错误-'instanceof'的右侧不可调用

时间:2020-06-24 19:51:03

标签: express supertest

当使用超级测试时,

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

  });
});

我得到"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'

这只是超级测试,使用Postman时API可以正常工作。

此调用的其余代码,

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

Supertest和Typescript是否缺少配置?

2 个答案:

答案 0 :(得分:0)

这种方法行得通,

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

答案 1 :(得分:0)

如果不想在代码中使用“await”,可以在回调函数中使用“done()”。 像这样。

    import app from "../../src/app";
    import request from "supertest";
    
    describe("GET / - a simple api endpoint", () => {
      it("Hello API Request", (done) => {
        const result = request(app)
        .get("/api/location/5eda6d195dd81b21a056bedb")
        .then((res) => {
          console.log(res);
          expect(res.text).toEqual("hello");
          expect(res.status).toEqual(200);
          done();
        //done() function means this test is done.
        })
      });
    });
相关问题