【问题标题】:(Mocha/Chai/Node.js) Why does the test pass even when there's an error?(Mocha/Chai/Node.js) 为什么即使有错误也能通过测试?
【发布时间】:2020-03-20 23:14:35
【问题描述】:

我是使用 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”的预期值,但测试仍然以某种方式通过,仅显示“@987654325 @"

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

expected 'Hello' to equal 'Hello world'

  1 passing (33ms)

cmd output - test result

我在测试的工作方式上有什么做错或误解的地方吗?

【问题讨论】:

    标签: node.js mocha.js chai


    【解决方案1】:

    正如docs 所说,当抛出错误时,您需要使用错误参数调用完成。因此,不要在调用 async 函数之后调用 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);
      })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-05
      • 2018-01-31
      • 1970-01-01
      • 2019-10-13
      相关资源
      最近更新 更多