【问题标题】:MochaJS: Rejected promises not triggering a failed testMochaJS:被拒绝的承诺不会触发失败的测试
【发布时间】:2019-04-23 06:54:40
【问题描述】:

我在 Mocha 和 Supertest 中使用 async-await 语法。这是我有问题的测试:

it('Test POST/friends route: should add a friendship', async function () {       
    const lastFriendship =   await models.Friendship.findAll({limit: 1,where: {},order: [ [ 'createdAt', 'DESC' ]]})
    const lastFriendId = lastFriendship[0].id

    await request(app)
        .post('/friends')
        .set('Authorization', token)
        .send({ friendId: 998 })
        .expect(200)
        .expect(async (res) => {
            console.log('res.data', res.body.data.id)
            const newFriendId = res.body.data.id
            expect(res.body.data.friendId).toEqual(998)
            expect(res.body).toHaveProperty('error', null);
            expect(newFriendId - lastFriendId).toBe(2)//This should fail the test.
        })        
})

现在写的最后一个断言应该无法通过测试,但是我收到了这个错误:

UnhandledPromiseRejectionWarning:错误: expect(received).toBe(expected) // Object.is 相等

我尝试将整个东西放在 try-catch 块中,但没有成功。我显然错过了这里的机制。

我的代码有什么问题?

编辑:从期望的回调函数中删除“异步”,解决它,虽然我不知道为什么在回调中抛出异常不会在这里被捕获。

【问题讨论】:

    标签: node.js async-await mocha.js supertest


    【解决方案1】:

    我认为您需要将 res.body 解析为 JSON。

    【讨论】:

    • 不,问题是我使用异步函数作为期望回调。一旦我删除它 - 它就可以工作。但我不知道为什么会发生这种情况。
    • 我在 mocha 中使用异步函数。他们很好。我看不出在函数签名中没有异步的情况下如何进行等待。
    • 是的,但我正在谈论对最后一个期望调用的回调。我不在那里使用“等待”。无论如何,从中删除异步解决了它,这意味着我并不真正了解异常和承诺是如何工作的:D
    • 是的,我也有类似的问题。就在我认为我知道它们是如何工作的时候,一个人咬了我。
    猜你喜欢
    • 2017-12-29
    • 2018-02-25
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    • 1970-01-01
    • 2018-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多