首页 > 解决方案 > Chai/Mocha:尽管识别到 AssertionError,但我的测试不会抛出错误

问题描述

我正在编写一些测试,一切进展顺利,但如果我尝试断言我知道是非常错误的东西,测试将通过,但我也会收到编译器抛出 AssertionError 的通知。但是,它实际上并没有通过测试。

我尝试返回期望短语,但我对它为什么不起作用感到有点困惑,感觉它应该很简单。

describe('api/users/changeAccountDetails', function() {
    beforeEach(()=>{
        return chai.request(app)
        .post('/api/users/signup')
        .send({
            firstName,
            lastName,
            username,
            password
        })
        .then(res => {
            console.log('a ok');
        })
        .catch(err => console.error(err));

    });

    afterEach(()=> {
        return User.deleteOne({})
    })


    describe('POST', ()=>{
        it('should update the firstName when given a string', ()=>{

        return chai.request(app)
        .post('/api/users/changeAccountDetails')
        .send({
            username,
            firstName: "Samus",
            lastName
        })
        .then(res => {
            console.log('b ok');
            //TODO: figure out why this isn't throwing an error if I make the number something else

            console.log(res.body);
            expect(res.body.code).to.equal(201);
            expect(res.body.user.firstName).to.equal('Michale');


        })
        .catch(err => console.error(err));  
        })
    });
})

响应如下所示:

b ok
{ code: 201,
  user:
   { firstName: 'Samus',
     lastName: 'User',
     _id: '5da947f7544bce4b6d71111f',
     username: 'exampleUser',
     password:
      '$2a$10$ABQzLOInfORJjsKd5Q3A9ejutCo22EVThHYLsEPPbqpVK717yJNGy',
     cats: [],
     __v: 0 } }
{ AssertionError: expected 'Samus' to equal 'Michale'
    at chai.request.post.send.then.res (/home/adrian/Development/gdc2API/test/test-users.js:186:52)
    at process._tickCallback (internal/process/next_tick.js:68:7)
  message: 'expected \'Samus\' to equal \'Michale\'',
  showDiff: true,
  actual: 'Samus',
  expected: 'Michale' }
        ✓ should update the firstName when given a string

closing the server

标签: node.jsmongodbmocha.jschai

解决方案


抛出的错误实际上被以下块捕获:

.catch(err => console.error(err));

由于该块,错误不会传播,因此测试成功。删除该块应该可以解决您的问题。


推荐阅读