Testing Asynchronous Jasmine Callbacks

I am 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 asynchronous code. I need to check the result of the function when the application is completed. Is there any way to do this? Currently my module is as follows:

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 as follows:

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

Obviously, the test is not awaiting execution. How to check asynchronous executable function through Jasmine? Also, am I using a state variable correctly? I'm lost in the asynchronous stack, and I'm not sure where I can use ' this '.

+6
source share
1 answer

I would recommend taking a look at the async section in jasmine docs . Thus, with this information, we can use the done callback to wait until the execution is complete before testing, for example:

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

Source: https://habr.com/ru/post/979248/


All Articles