我在尝试在 Mocha 单元测试中使用 assert.throws 时遇到了麻烦,
我有这个方法:
var getMetadatas = function (file, callback) {
fs.readFile(file, {encoding: 'utf-8'}, function(err, data){
// stuff
if (somethingWentWrong)
throw new Error('Something went wrong')
// callback call
})
}
在我的单元测试中,我有:
it('should throw an error when passing a bad formatted file', function(){
assert.throws(
getMetadatas('someBadFormattedFile', function(metadatas){})
)
})
我得到的结果是随机的,有时会抛出错误(我得到 Uncaught Error :出了问题
)并且测试失败,有时会通过。
我尝试了其他一些方法,例如通过回调传递错误并执行以下操作:
var fn = function(){
parse.getMetadatas('test/test_incorrect.md', function (err, metas) {
if (err) throw err
})
}
assert.throws( function() { fn() }, Error )
我得到了输出:AssertionError:缺少预期的异常(错误)..
所以我猜他没有看到任何东西......
让 assert.throws
按照我的预期工作的唯一方法是使用同步函数:
assert.throws(
function () {throw new Error('error')}
)
我想知道它是否必须使用 done()
执行某些操作,但即使在我的回调中调用它,也没有成功。我错过了什么吗?
最佳答案
如果我们删除注释,这一切都非常简单,只需 3-4 行代码。您只需遵循我在下面介绍的具体模式即可。
it('Should throw error from an asynchronous function', async function() {
try {
await someAsycnFunction();
/**
* The next line forces the test fail in case someAsyncFucntion() does not throw.
*/
assert.fail('The expected Error was not thrown.');
} catch (err) {
/**
* (optional) Here we assert the error object prototype name for the cases when we
* want to check the error type is the expected one (e.g. we have
* extended the base JS exception to make our own exception).
*/
assert.typeOf(err, 'Error', 'someAsycnFunction did not throw expected error.');
/**
* (optional) Here we assert that the error message is the expected one.
*/
assert.include(err.message, 'ExpectedErrorMessage', 'someAsycnFunction error message does not match the expected one.');
/**
* (optional) Here we re-throw the caught error to assert it includes the
* expected error message substring (as a regex).
*/
assert.throws(() => {
throw err;
}, Error, /ExpectedErrorMessage/);
}
});
最基本的实现可能只在 catch
block 中包含您选择的一个断言。这种方法的关键是将抛出异步函数包装在 try/catch
中,并在 try
block 中强制测试失败。
关于javascript - 异步方法上的assert.throws,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19187111/