我看到的最简单的解决方案是覆盖全局函数 describe 和 it 以使它们接受第三个可选参数,该参数必须是布尔值或返回布尔值的函数 - 以判断当前套件是否/spec 应该被执行。覆盖时,我们应该检查这第三个可选参数是否解析为true,如果是,则调用xdescribe/xit(或ddescribe/iit,取决于 Jasmine 版本),这是 Jasmine 的方法跳过套件/规范,而不是原始的describe/it。这个块必须在测试之前执行,但在 Jasmine 被包含到页面之后。在 Karma 中,只需将此代码移动到一个文件中,并将其包含在 karma.conf.js 中的测试文件之前。代码如下:
(function (global) {
// save references to original methods
var _super = {
describe: global.describe,
it: global.it
};
// override, take third optional "disable"
global.describe = function (name, fn, disable) {
var disabled = disable;
if (typeof disable === 'function') {
disabled = disable();
}
// if should be disabled - call "xdescribe" (or "ddescribe")
if (disable) {
return global.xdescribe.apply(this, arguments);
}
// otherwise call original "describe"
return _super.describe.apply(this, arguments);
};
// override, take third optional "disable"
global.it = function (name, fn, disable) {
var disabled = disable;
if (typeof disable === 'function') {
disabled = disable();
}
// if should be disabled - call "xit" (or "iit")
if (disable) {
return global.xit.apply(this, arguments);
}
// otherwise call original "it"
return _super.it.apply(this, arguments);
};
}(window));
及用法示例:
describe('foo', function () {
it('should foo 1 ', function () {
expect(true).toBe(true);
});
it('should foo 2', function () {
expect(true).toBe(true);
});
}, true); // disable suite
describe('bar', function () {
it('should bar 1 ', function () {
expect(true).toBe(true);
});
it('should bar 2', function () {
expect(true).toBe(true);
}, function () {
return true; // disable spec
});
});
See a working example here
我还偶然发现了this issue,它的想法是为describe 和it 添加一个链方法.when(),它的作用与我上面描述的几乎相同。它可能看起来更好,但实现起来有点困难。
describe('foo', function () {
it('bar', function () {
// ...
}).when(anything);
}).when(something);
如果您真的对第二种方法感兴趣,我很乐意多尝试一下并尝试实现链.when()。
更新:
Jasmine 使用第三个参数作为超时选项 (see docs),所以我的代码示例正在替换此功能,这是不行的。我更喜欢 @milanlempera 和 @MarcoCI 的答案,我的似乎有点老套而且不直观。我会尽快更新我的解决方案,以免破坏与 Jasmine 默认功能的兼容性。