简体   繁体   English

茉莉花异步测试

[英]Jasmine Async Testing

I'm attempting to test a value that is set asynchronously using Jasmine 2's new done() callback. 我正在尝试测试使用Jasmine 2的新的done()回调异步设置的值。

I've based my test after the example Jasmine gives in their documentation ( http://jasmine.github.io/2.0/upgrading.html#section-Asynchronous_Specs ): 我根据Jasmine在其文档( http://jasmine.github.io/2.0/upgrading.html#section-Asynchronous_Specs )中给出的示例进行了测试:

it('can set a flag after a delay', function(done) {

  var flag = false,
  setFlag = function() {
    //set the flag after a delay
    setTimeout(function() {
        flag = true;
        done();
    }, 100);
  };

  setFlag();
  expect(flag).toBe(true);
});

I'm getting the result "Expected false to be true", so I'm guessing that it's not waiting for the done() callback to be invoked before checking the value of the flag. 我得到的结果是“ Expected false to true”,所以我猜测在检查标志值之前,它没有等待调用done()回调。

Does anyone know why this test is failing? 有谁知道为什么这个测试失败了?

Thanks! 谢谢!

It's because you're running your assertion as soon as setTimeout has been call, thus you're not giving it enough time to invoke the callback that sets flag to true. 这是因为在调用setTimeout后就立即运行断言,因此您没有给它足够的时间来调用将flag设置为true的回调。 The below code will work (run the below code at TryJasmine to see how it behaves): 下面的代码将起作用(在TryJasmine上运行下面的代码以查看其行为):

describe('flag delays', function () {
  it('can set a flag after a delay', function(done) {
    var flag = false,
    setFlag = function() {
      //set the flag after a delay
      setTimeout(function() {
          flag = true;
          expect(flag).toBe(true);
          done();
      }, 100);
    };

    setFlag();
  });
});

Going forward, Jasmine has a waitsFor method to facilitate testing timers. 展望未来,Jasmine有一个waitsFor方法来方便测试计时器。 Even better, Sinon.JS provides functionality for faking times , which enables to skip setTimeout invocations and verify any behaviour without creating duration-based dependencies in your tests. 更好的是, Sinon.JS提供了虚假 时间功能,该功能可以跳过setTimeout调用并验证任何行为,而无需在测试中创建基于持续时间的依赖项。 Additionally, you'll be able to write assertions at the end of your tests as your did in your question, which will massively improve readability. 此外,您可以像在问题中一样在测试结束时编写断言,这将大大提高可读性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM