javascript 使用 Jasmine 测试异步回调

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27344872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:21:53  来源:igfitidea点击:

Testing Asynchronous Callbacks with Jasmine

javascriptasynchronousjasmine

提问by JQuery Mobile

I'm using Jasmine 2.1. I am trying to use Jasmine 2.1 to test a module. One of my modules has a function that executes code asynchronously. I need to test the result of the function when the app is done executing. Is there a way to do this? Currently, my module looks like this:

我正在使用茉莉花 2.1。我正在尝试使用 Jasmine 2.1 来测试模块。我的一个模块有一个异步执行代码的函数。我需要在应用程序执行完毕后测试函数的结果。有没有办法做到这一点?目前,我的模块如下所示:

var otherModule = require('otherModule');
function MyModule() {
}

MyModule.prototype.state = '';
MyModule.prototype.execute = function(callback) {
  try {
    this.state = 'Executing';
    var m = new otherModule.Execute(function(err) {
      if (err) {
        this.state = 'Error';
        if (callback) {
          callback(err);
        }
      } else {
        this.state = 'Executed';
        if (callback) {
          callback(null);
        }
      }
    });
  } catch (ex) {
    this.state = 'Exception';
    if (callback) {
      callback(ex);
    }
  }
};

module.exports = MyModule;

I am trying to test my Module with the following:

我正在尝试使用以下内容测试我的模块:

var MyModule= require('./myModule');
describe("My Module", function() {
  var myModule = new MyModule();
  it('Execute', function() {
    myModule.execute();
    expect(myModule.state).toBe('Executed');
  });
});

Clearly, the test is not awaiting for the execution to occur. How do I test an asynchronous executed function via Jasmine? In addition, am I using the state variable properly? I get lost in the asynchronous stack and I'm unsure where I can use 'this'.

显然,测试不是在等待执行发生。如何通过 Jasmine 测试异步执行的函数?另外,我是否正确使用了状态变量?我迷失在异步堆栈中,不确定在哪里可以使用“ this”。

回答by David McMullin

I would recommend taking a look at the async section of the jasmine docs. So, with this information we can use a donecallback to wait for the execution to finish before testing anything, like this:

我建议查看jasmine docsasync 部分。因此,有了这些信息,我们可以done在测试任何东西之前使用回调来等待执行完成,如下所示:

var MyModule= require('./myModule');
describe("My Module", function() {
  var myModule = new MyModule();
  it('Execute', function(done) {
    myModule.execute(function(){
        expect(myModule.state).toBe('Executed');
        done();
    });
  });
});