Chai returnedWith 未正确链接

问题描述 投票:0回答:1

我已经阅读了大量的帖子和文档,但似乎无法弄清楚为什么这段代码不能像我认为的那样工作。

const chai = require('chai');
const expect = chai.expect;
const chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);

async function foo(val) {

    if (!val) {
        const err = new Error();
        err.status = 404;
        throw err;
    }

    return new Promise(resolve => sleepSetTimeout_ctrl = setTimeout(resolve, 10));
}

describe('does not work', () => {
    it('throws', async () => {
        await expect(foo()).to.be.rejectedWith(Error).and.have.property('status');
    });
});

如果我在

rejectedWith(Error)
结束期望,它工作正常,但尝试测试该属性是否存在失败,并显示:
AssertionError: expected {} to have property 'status'

javascript chai-as-promised
1个回答
0
投票

发生这种情况是因为

rejectedWith
的返回值是
PromisedAssertion
- 您断言 promise(类对象)是否具有
status
属性。实际上,我收到了一条稍微有用的消息,这使得这一点更加清晰:

AssertionError: expected Promise{…} to have property 'status'

您还可以看到,如果您测试它确实具有的属性,例如

then

await expect(foo()).to.be.rejectedWith(Error).and.have.property('then');  // ✅

要对实际错误对象进行断言,您需要再次使用

chai-as-promised
的链接器,例如:

return expect(foo()).to.be.rejectedWith(Error).and.eventually.have.property("status");  // ✅
                                               // ^---------^
© www.soinside.com 2019 - 2024. All rights reserved.