简体   繁体   中英

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

I'm very new in testing using Mocha and Chai. Given the code below:

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

And to test the code above, I tried to use this:

//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();
    });
});

I believe that the test should fail as the message "Hello" being sent (as res.body.message ) is not equal to the expected value of "Hello world" yet the test still somehow passed with just an indication that " 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

Is there something that I did wrong or misunderstand with how testing works?

As docs says, you need to call done with error argument, when error thrown. So instead of calling done after calling async function (which, by the way, will be executed even before async result comes), you need to call inside then and catch callbacks:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM