gpt4 book ai didi

javascript - 如何使用 mocha、promise 和 catch block 防止误报

转载 作者:行者123 更新时间:2023-11-28 00:13:14 25 4
gpt4 key购买 nike

我想利用 Mocha 内置的 Promise 支持,但当我想测试 Promise 链中的 catch 分支时,我很难处理误报。

This问题最接近我想要的,但解决方案要求我项目中的每个开发人员添加一个会引发错误的 then ,并确保该错误不会意​​外地通过测试。

因此,我不得不恢复使用 done 风格的测试,它依赖内置的超时来捕获错误而不是断言。这不太理想,但消除了误报的可能性。

var RSVP = require('RSVP');

function request (shouldSucceed) {
if (shouldSucceed) {
return RSVP.Promise.resolve('success');
} else {
return RSVP.Promise.reject(new Error('failure'));
}
}

describe('request', function () {
it('throws an error if shouldSucceed is not provided', function () {
// this test is incorrectly calling `request`
// which leads to it passing without actually testing
// the behaviour it wants to
return request(true)
.catch(function (err) {
expect(err).to.be.an.instanceof(Error)
});
});

it('throws an error if shouldSucced is not provided (manual then block)', function () {
// this test tacks a `then` onto the chain, to ensure `request`
// actually throws an error as expected
// unfortunately, it still passes since the assertion needs to do
// a little extra work to ensure the type of error thrown is the
// expected error
return request(true)
.then(function () {
throw new Error('Not expected');
})
.catch(function (err) {
expect(err).to.be.an.instanceof(Error)
});
});

it('throws an error if shouldSucceed is not provided (done syntax)', function (done) {
// this assertion fails (as it should)
// due to a timeout
return request(true)
.catch(function () {
expect(err).to.be.an.instanceof(Error);
done()
});
});
});

输出:

  request
✓ throws an error if shouldSucceed is not provided
✓ throws an error if shouldSucced is not provided (manual then block)
1) throws an error if shouldSucceed is not provided (done syntax)


2 passing (2s)
1 failing

1) request throws an error if shouldSucceed is not provided (done syntax):
Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.

是否有一种更简洁的方法来告诉 mocha 我期望在 catch block 中发生某些事情,并且成功解决 promise 应该是测试失败?

最佳答案

您正在寻找

it('request(false) should throw an error', function () {
return request(false).then(function() {
throw new Error('unexpected success');
}, function(err) {
expect(err).to.be.an.instanceof(Error)
});
});

参见When is .then(success, fail) considered an antipattern for promises?获取与您当前代码的差异的解释。

关于javascript - 如何使用 mocha、promise 和 catch block 防止误报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30686380/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com