Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test a function which calls async function using Jasmine

How to test this function:

var self = this;
self.someVariable = "initial value";
self.test = function() {
   self.functionWhichReturnsPromise().then(function() {
     self.someVariable = "new value";
   });
}

I have test case like below, I know it is wrong because before promise is resolved, the assert statement will be executed by jasmine:

it("should test the function test", function (done) {
    var abc = new ABC();
    abc.test();
    expect(abc.someVariable).toBe('new value');
});

Note that I do not want to use setTimeout() or any sleep methods.

like image 376
Mumzee Avatar asked Oct 24 '25 04:10

Mumzee


2 Answers

Two things, you need your test function to return the Promise and you need to use an arrow function or .bind the callback to the parent function (otherwise the this in this.someVariable will refer to the callback function):

this.test = function() {
   return this.functionWhichReturnsPromise().then(() => {
     this.someVariable = "new value";
   });
}

or

this.test = function() {
   return this.functionWhichReturnsPromise().then(function() {
     this.someVariable = "new value";
   }.bind(this));
}

Then in your test you can do:

it("should test the function test", function (done) {
    var abc = new ABC();
    abc.test().then(function() {
       expect(abc.someVariable).toBe('new value');
       done();
    });
});
like image 61
Rob M. Avatar answered Oct 26 '25 17:10

Rob M.


You can just spy on the function which returns the promise.

describe('when test method', function() {
  beforeEach(function() {
    this.promiseResult = Math.random();
    spyOn(ABC.prototype, 'functionWhichReturnsPromise')
      .and.returnValue(Promise.resolve(this.promiseResult));
  })

  it('then should change someVariable with the result of functionWhichReturnsPromise', function() {
    var abc = new ABC();
    abc.test();
    expect(abc.someVariable).toBe(this.promiseResult);
  });
});

No need to wait the promise, inside this unit test, you are not interested in how functionWhichReturnsPromise actually works, you only want to see that the result of calling functionWhichReturnsPromise will update someVariable value.

Have fun and luck

like image 44
cnexans Avatar answered Oct 26 '25 18:10

cnexans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!