问题描述
我正在使用 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 测试异步执行的函数?另外,我是否正确使用了状态变量?我迷失在异步堆栈中,不确定在哪里可以使用 'this
'.
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 测试异步回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!