【问题标题】:Chai-http request returning undefinedChai-http 请求返回未定义
【发布时间】:2022-01-09 04:56:22
【问题描述】:

下面是我的代码:

server.js

const app = express();
app.listen(port, () => {
  logger.info(`App running on http://localhost:${port}`);
});

export default app;

test.js

import server from "../../src/index.js";

chai.use(chaiHttp);

describe("GET Balance API Tests", () => {
  beforeEach(() => {
    const userBalance = mockUserBalances;
  });

  it("should return correct value", async () => {
    const res = await chai.request(server).get("/balance/user-1");
    console.log(res.status);  // this correctly returns 200
    res.status.should.equal(200);  // this throws an error stating res is undefined
  });
});

我在这里做错了什么?为什么当我尝试做出任何断言时 res 总是未定义?

【问题讨论】:

    标签: javascript node.js testing mocha.js chai


    【解决方案1】:

    由于res.status 是“200”,我认为它不会有should 属性。我认为正确的断言应该是这样的:

    expect(res).to.have.status(200);
    

    【讨论】:

    • 谢谢,这成功了!我可以问为什么吗?我也尝试过 res.should.have.status(200) 但它返回相同的错误(无法读取未定义的属性“有”),这意味着它将 res 视为未定义
    • 如果错误提示“Cannot read property 'have' of undefined”,实际上意味着res.should 未定义,因为代码无法从res.should 读取'have'。如果 res 未定义,则错误将是“无法读取属性‘应该’未定义”。这有意义吗?
    • 知道了,这意味着我可能没有正确导入“应该”,非常感谢!
    • expect 为您提供shouldtohave 等...res 本身只是一个响应。
    猜你喜欢
    • 1970-01-01
    • 2019-06-17
    • 2018-08-09
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-26
    • 1970-01-01
    相关资源
    最近更新 更多