我正在尝试编写一个异步测试,这是我以前从未做过的。在英语中,测试说明了这一点:
因此,通过阅读文档,并查看其他一些代码,我认为这就是我应该写它的方式。
it("should create a timer not start", function (done) {
var fail = false, timer;
// if this test is passing, this should do nothing
runs(function(){
timer = new Timer(function () {
fail = true;
timer.pause();
}, 500);
});
// if this test is passing, fail should never be true
waitsFor(function(){
return fail;
}, 1000);
// this should be called after 1 second because the previous times out
runs(function(){
expect(fail).toBeFalsy();
});
});
然而,waitsFor超时,因为失败永远不应该是真的。我需要waitsFor等待整秒,然后expect语句可以运行,但我需要超时才是好事,而不是失败(Jasmine将其报告为)。
如何使用Jasmine执行此操作?
答案 0 :(得分:1)
编辑2017-07-24
基于@Yavin5的评论,这个答案对Jasmine v1有效。
要升级到Jasmine v2,请参阅文档。 https://jasmine.github.io/2.0/upgrading.html#section-9
对于Jasmine V2文档,请访问https://jasmine.github.io/2.0/introduction.html#section-Asynchronous_Support
您需要添加一个标志,该标志在异步操作完成后将变为true。这就是waitsFor
正在等待的东西。我会建议像
it("should create a timer not start", function (done) {
var fail = false, timer, flag;
// if this test is passing, this should do nothing
runs(function(){
flag = false;
timer = new Timer(function () {
fail = true;
timer.pause();
}, 500);
setTimeout(function() {
flag = true;
}, 1000);
});
// if this test is passing, fail should never be true
waitsFor(function(){
return flag;
}, 1100);
// this should be called after 1 second because the previous times out
runs(function(){
expect(fail).toBeFalsy();
});
});