[英]Testing metalsmith plugin that should throw an error using mocha
I'm writing a metalsmith plugin and its associated test suite with mocha. 我正在用Mocha编写Metalsmith插件及其关联的测试套件。
The plugin should throw an exception if it lacks configuration: 如果缺少配置,则插件应引发异常:
function plugin(config) {
...
return function(files, metalsmith, done) {
...
done(new Error("config error"));
}
}
and I try to test it with mocha this way: 我尝试用这种方式用摩卡咖啡进行测试:
describe('my plugin', function() {
it('should throw an exception', function(done) {
var metalsmith = Metalsmith('test/fixtures/basic');
metalsmith
.use(myplugin({
someconfig: {
}))
.build(function(err,files) {
assert(err);
done();
});
});
});
When I run the test I have this result: 运行测试时,我得到以下结果:
my plugin
✓ should throw an exception
1) should throw an exception
1 passing (31ms)
1 failing
1) my plugin should throw an exception:
Error: done() called multiple times
So it seems the test is ok but somehow is run another time, failing this time... 所以看起来测试还可以,但是又一次又运行了一次,这次失败了...
The problem was that the error was throwed inside a foreach loop, causing done() to be called multiple times: 问题是该错误被抛出到一个foreach循环内,导致done()被多次调用:
Object.keys(files).forEach(function (file) {
...
done(new Error("config error"));
...
}
Adding a simple return does not work because you can't return from a foreach loop. 添加简单的返回不起作用,因为您无法从foreach循环中返回。
So using a simple for loop instead of the foreach, returning on the first error: 因此,使用简单的for循环而不是foreach,返回第一个错误:
for (var file in files) {
...
return done(new Error("config error"));
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.