在cucumber.js中,我定义了一个步骤,例如:
this.When(/^I call getCollections$/, function(callback) {
this.repo.getCollections( function( err, results ) {
this.results = results;
callback( err );
}.bind( this ) );
});
但是如果对this.repo.getColections
的调用永远不会回调我的函数,那么callback
将永远不会执行,并且cucumber.js会立即以正常退出代码退出。
如果永远不会调用回调,有没有办法让cucumber.js失败?
答案 0 :(得分:1)
沿着这些方向做的事情应该可以解决问题:
this.Given(/^blah$/, function (callback) {
var failed = false;
var timeout = setTimeout(function () {
callback(new Error("Timed out"));
}, 500);
doSomethingThatMightNeverCallback(function (err) {
if (!failed) {
clearTimeout(timeout);
callback(err);
}
});
});
您可以轻松地重新定义Cucumber的Given / When / Then:
var cucumber = this;
var Given = When = Then = defineStep;
function defineStep (name, handler) {
cucumber.defineStep(name, function () {
var world = this;
var args = Array.prototype.splice.call(arguments, 0);
var callback = args.pop();
var failed = false;
var timeout = setTimeout(function () {
callback(new Error("Timed out"));
}, 500);
args.push(function (err) {
if (!failed) {
clearTimeout(timeout);
callback(err);
}
});
handler.apply(world, args);
});
}
然后使用Given()
,When()
和Then()
代替this.Given()
等来定义您的步骤定义:
Given(/^foo$/, function (callback) {
setTimeout(callback, 400); // this will pass
});
Given(/^bar$/, function (callback) {
setTimeout(callback, 500); // this will fail
});
When(/^baz$/, function (callback) {
doYourStuff(callback);
});
我按照预期在第2步失败了以下方案:
Feature: Baz
Scenario:
Given foo
And bar
输出:
cucumber.js test.feature
.F
(::) failed steps (::)
Error: Timed out
at null._onTimeout (/Users/jbpros/tmp/abc/code.js:13:18)
at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)
Failing scenarios:
/Users/jbpros/tmp/abc/test.feature:3 # Scenario:
1 scenario (1 failed)
2 steps (1 failed, 1 passed)
HTH,
答案 1 :(得分:0)
以下是我最终做的事情:
在utils.js模块中,我公开了一个函数
function specifyTimeout( scenario, timeout ) {
scenario.Before( function( callback ) {
scenario.timeout = setTimeout( function() { throw new Error("Timed out"); }, 500 );
callback();
} );
scenario.After( function( callback ) {
clearTimeout( scenario.timeout );
callback();
} );
}
然后在我的步骤定义的顶部,我只是这样做:
module.exports = function() {
utils.specifyTimeout( this, 500 );
. . .