Jasmine 测试失败后执行代码 [英] Execute code after Jasmine test failure
问题描述
只有在 Jasmine 测试失败时才可以做某事吗?与在 it()
之后执行的 afterEach()
并列,无论结果如何,我都在寻找一些仅在 it()<之后执行代码的方法/code> 有一个失败的期望.
Is it possible to do something only if a Jasmine test fails? Juxtaposed with afterEach()
which executes after an it()
regardless of outcome, I'm looking for some way to execute code only after an it()
has a failed expectation.
这个问题不是 Angular 特定的,但在我的场景中,我正在测试一个使用 $log
输出调试消息的 Angular 服务.我不想让我的控制台因测试成功而变得混乱,而只想显示失败测试的附加信息.
This question is not Angular-specific, but in my scenario I am testing an Angular service which outputs debug messages using $log
. I don't want to clutter my console for tests that are successful, but only show the additional information for failing tests.
describe("MyService", function() {
var MyService, $log;
beforeEach(function() {
inject(function (_MyService_, _$log_) {
MyService = _MyService_;
$log = _$log_;
});
});
afterEach(function () {
if (/* test failed */) {
//console.log($log.debug.logs);
}
});
it("should output debug logs when this fails", function() {
//do something with MyService that would put a message in $log
expect(false).toBe(true);
});
});
我正在运行 Jasmine 2.2.0.
I'm running Jasmine 2.2.0.
这里是一个非常简单的小提琴,它显示了 Jasmine 1.3 jasmine.getEnv().currentSpec
解决方案不再起作用.
here's a very simple fiddle which shows the Jasmine 1.3 jasmine.getEnv().currentSpec
solution no longer working.
推荐答案
这是在 Jasmine 2 中重新启用 jasmine.getEnv().currentSpec
的 hack(有点,result
不是完整的 spec
对象,但包含 id
、description
、fullName
、failedExpectations
和 passedExpectations
):
Here's a hack to re-enable jasmine.getEnv().currentSpec
in Jasmine 2 (sort of, result
isn't the full spec
object, but contains id
, description
, fullName
, failedExpectations
, and passedExpectations
):
jasmine.getEnv().addReporter({
specStarted(result) {
jasmine.getEnv().currentSpec = result;
},
specDone() {
jasmine.getEnv().currentSpec = null;
}
});
这篇关于Jasmine 测试失败后执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!