使用Jasmine测试异步回调 [英] Testing Asynchronous Callbacks with Jasmine
问题描述
我正在使用Jasmine 2.1。我正在尝试使用Jasmine 2.1来测试模块。我的一个模块有一个异步执行代码的函数。我需要在应用程序执行完毕后测试函数的结果。有没有办法做到这一点?目前,我的模块如下所示:
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:
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');
});
});
显然,测试不等待执行发生。如何通过Jasmine测试异步执行的函数?另外,我是否正确使用状态变量?我迷失在异步堆栈中,我不确定在哪里可以使用'这个
'。
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
'.
推荐答案
我建议你看一下茉莉花文档的异步部分一>。因此,有了这些信息,我们可以使用 done
回调等待执行完成,然后再测试任何内容,如下所示:
I would recommend taking a look at the async section of the jasmine docs. So, with this information we can use a done
callback to wait for the execution to finish before testing anything, like this:
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();
});
});
});
这篇关于使用Jasmine测试异步回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!