我正在测试一个作为承诺的一部分返回的函数。我正在使用chai。
我可以测试该函数是否有效,但我无法测试它是否正确抛出错误。
我要测试的函数,省略了许多与承诺相关的代码:
// function that we're trying to test
submitTest = (options) => {
// missingParam is defined elsewhere. It works - the error is thrown if screenshot not passed
if (missingParam(options.screenShot)) throw new Error('Missing parameter');
return {};
}
我的测试:
describe('SpectreClient()', function () {
let client;
before(() => client = SpectreClient('foo', 'bar', testEndpoint));
// the client returns a function, submitTest(), as a part of a promise
/*
omitting tests related to the client
*/
describe('submitTest()', function () {
let screenShot;
before(() => {
screenShot = fs.createReadStream(path.join(__dirname, '/support/test-card.png'));
});
// this test works - it passes as expected
it('should return an object', () => {
const submitTest = client.then((response) => {
return response.submitTest({ screenShot });
});
return submitTest.should.eventually.to.be.a('object');
});
// this test does not work - the error is thrown before the test is evaluated
it('it throws an error if not passed a screenshot', () => {
const submitTest = client.then((response) => {
return response.submitTest({});
});
return submitTest.should.eventually.throw(Error, /Missing parameter/);
});
});
})
测试的输出-
// console output
1 failing
1) SpectreClient() submitTest() it throws an error if not passed a screenshot:
Error: Missing parameter
如何测试错误是否被正确抛出?我不确定这是摩卡的问题还是承诺的问题还是承诺的问题。非常感谢你的帮助。
承诺处理程序内部引发的异常被转换为承诺拒绝。submitTest
在对client.then
的回调中执行,因此它引发的异常成为承诺拒绝。
所以你应该这样做:
return submitTest.should.be.rejectedWith(Error, /Missing parameter/)