【问题标题】:Mocha Chai .end() function not being executedMocha Chai .end() 函数未执行
【发布时间】:2021-07-16 06:39:28
【问题描述】:

我一直在尝试为 Nodejs API 编写 Mocha chai 测试。它以前是使用 Supertest 编写的。但是,在这两种情况下,即使我指定了错误的预期参数,测试也总是通过。

这里是使用 chai 的测试函数


const chai = require('chai');
const chaiHttp = require('chai-http');

chai.should();

chai.use(chaiHttp);


const app = require("../app");
const user = {
  first_name: "Name",
    last_name: "Lastname",
    email: "email",
    password: "password"
};

describe("Registration  Test", () => {
  it("Responds with status of registration", (done) => {
    chai.request(app)
    .post('/register')
    .send(user)
    .end((err,res) => {
      if(err) done(err);
      res.should.have.status.eq(200);
      res.body.should.have.property('success').eq(true);
      done();   <------------ Here it doesn't work. It returns For async tests and hooks, ensure "done()" is called error
    });
    done(); <----------- But here it works

  });


});


API 以带有成功、消息和状态属性的正文进行响应。但无论我在 chai 中写什么检查,测试总是通过。另外,当我添加 done();在 end() 内部,找不到它,但是当我在 end() 外部写它时,它会运行。所以我假设我的代码永远不会进入 .end()。

【问题讨论】:

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


    【解决方案1】:

    所以,我犯了一个愚蠢的错误。我让服务器使用 npm start 手动运行,并且端口 5000 被占用。当我使用 chai.request(app) 运行测试脚本时,端口已经被占用,我后来才意识到这一点。但是,我是这样使用 async/await 编写脚本的,

    describe("Tests for Doctor and Patient Registration", () => {
      it("Existing doctor registation fails", async () => {
        const res = await chai
          .request(app)
          .post("/register")
          .set("Content-type", "application/json")
          .set("Connection", "keep alive")
          .send(user[0]);
    
        expect(res.status).to.equal(200);
        expect(res.body).to.have.property("success", false);
        expect(res.body).to.have.property(
          "message",
          "A user with this email already exist, did you forget your password?"
        );
      });
     }

    【讨论】:

      【解决方案2】:

      您需要传递done 参数并仅在end 函数内调用它:

      it("Responds with status of doctor registration", function (done) {
        chai.request(app)
          .post('/register')
          .send(user)
          .end((err,res) => {
            should.not.exist(err);
            res.should.have.status.eq(200);
            res.body.should.have.property('success').eq(true);
          });
      });
      

      参考https://www.chaijs.com/plugins/chai-http/#caveat

      【讨论】:

      • 我确实通过了。但是我得到了同样的错误,说超时,确保调用了 done()。
      猜你喜欢
      • 2015-03-21
      • 1970-01-01
      • 2017-02-14
      • 1970-01-01
      • 2015-06-02
      • 1970-01-01
      • 1970-01-01
      • 2018-10-02
      • 1970-01-01
      相关资源
      最近更新 更多