Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

javascript - Testing Asynchronous Callbacks with Jasmine

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');
  });
});

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'.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
    });
  });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...