【问题标题】:How to test errors with Chai?如何用 Chai 测试错误?
【发布时间】:2021-04-10 14:49:45
【问题描述】:

我正在测试一个获取用户的 api 路由。它运作良好。现在,如果我获取不存在的用户,我想测试路由是否会引发错误并显示正确的消息。该测试声称是肯定的,但我知道这不是因为我无法 console.log 结果或.end() 回调中的错误。这是测试和路线:

require("dotenv").config();
import chai from "chai";
import chaiHttp from "chai-http";
import connectToDatabase from "../database/connection";
import { app } from "../index";
import jwt from "jsonwebtoken";

chai.use(chaiHttp);
const api = chai.request(app);

before((done) => {
  connectToDatabase().then(() => done());
});

const token = jwt.sign(
  { _id: "123", locale: "en" },
  process.env.JWT_TOKEN_KEY,
  {
    expiresIn: "14d",
  }
);

describe("GET /user/:id", () => {
  it("return user information", () => {
    api
      .get("/user/607183db2020190b510bd9a5")
      .set("Cookie", `mycookie=${token};`)
      .end((err, res) => {
        chai.expect(res).to.have.status(200);
        chai.expect(res.body.user._id).to.equal("607183db2020190b510bd9a5");
      });
  });
  it("throws an error if the user doesn't exist", () => {
    api
      .get("/user/abc")
      .set("Cookie", `mycookie=${token};`)
      .end((err, res) => {
        console.log("res failed ok", res, "eeror", err); // this line never shows up
        chai.expect(err).to.throw("error.unknown");
      });
  });
});



// the route:
const getUser = async (
  req: GetUser,
  res: IResponse
): Promise<IResponse> => {
  try {
    const user = await UserControler.findUserById(req.params.id);
    return res.status(200).json({ user });
  } catch (err) {
    throw new Error("error.unknown");
  }
};

export default getUser;

如何解决这个问题?

【问题讨论】:

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


    【解决方案1】:

    如这里(警告部分)https://www.chaijs.com/plugins/chai-http/ 所述,在使用 end() 函数时需要使用 done。

    因为结束函数被传递了一个回调,所以断言被运行 异步。因此,必须使用一种机制来通知 回调已完成的测试框架。否则, 在检查断言之前测试将通过。

    这会导致您的测试等到 done() 被调用。 end() 函数在您的请求完成后运行。传递 done 参数使 mocha 等待直到 done() 被调用或超时。如果不使用,测试成功,无需等待响应。

    所以你应该在你的测试中这样做(注意第一次测试中的变化):

    describe("GET /user/:id", () => {
      it("return user information", (done) => {
        api
          .get("/user/607183db2020190b510bd9a5")
          .set("Cookie", `mycookie=${token};`)
          .end((err, res) => {
            chai.expect(res).to.have.status(200);
            chai.expect(res.body.user._id).to.equal("607183db2020190b510bd9a5");
            done(); // here
          });
      });
      it("throws an error if the user doesn't exist", (done) => {
        api
          .get("/user/abc")
          .set("Cookie", `mycookie=${token};`)
          .end((err, res) => {
            console.log("res failed ok", res, "eeror", err); // this line never shows up
            chai.expect(err).to.throw("error.unknown");
            done(); // and here 
          });
      });
    });
    
    

    将箭头函数用于测试函数也不是最佳做法。使用 function(){ 代替。检查这个原因https://mochajs.org/#arrow-functions

    【讨论】:

      猜你喜欢
      • 2017-10-23
      • 1970-01-01
      • 1970-01-01
      • 2013-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-02
      相关资源
      最近更新 更多