(Mocha/Chai/Node.js) 为什么有错误也能通过?

(Mocha/Chai/Node.js) Why does the test pass even when there's an error?

我对使用 Mocha 和 Chai 进行测试非常陌生。给定以下代码:

//app.js
app.get("/", (req, res) => {
    res.send({message:'Hello'});
});

为了测试上面的代码,我尝试使用这个:

//test.js
describe('App', () => {
    it('should get message "Hello world"', (done) => {
        chai.request(app).get('/').then((res) => {
            expect(res.body.message).to.be.equal('Hello world');
        }).catch(err => {
            console.log(err.message);
        })
        done();
    });
});

我认为测试应该失败,因为正在发送的消息 "Hello"(如 res.body.message)不等于 "Hello world" 的预期值,但测试仍然以某种方式通过只是表明“expected 'Hello' to equal 'Hello world'

//cmd output
  App
    √ should get message "Hello world"

expected 'Hello' to equal 'Hello world'

  1 passing (33ms)

cmd output - test result

我是否做错了什么或对测试的工作方式有误解?

正如docs所说,当抛出错误时,您需要使用错误参数调用完成。因此,不是在调用异步函数后调用 done(顺便说一下,它甚至会在异步结果出现之前执行),而是需要在 then 内部调用并捕获回调:

chai.request(app).get('/').then((res) => {
    expect(res.body.message).to.be.equal('Hello world');
    done()
  }).catch(err => {
    done(err);
    console.log(err.message);
  })