mercredi 7 septembre 2016

Check if timeout has deferred tasks Jasmine Unit testing

I have been writing unit tests with Jasmine for AngularJs. Here is the plunker I have created to simulate the problem I am facing:

http://ift.tt/2bXFCwD

My Unit test:

describe('MyService', function () {
    var myService;
    beforeEach(module('timeoutUnitTest'));
    beforeEach(inject(function (_MyService_, _$timeout_) {
        myService = _MyService_;
        timeout = _$timeout_;
    }));

     it('should not set timeout for polling when not sent in', inject(function () {

        myService.getData(1,30)
         timeout.flush(10); 
        //spyOn(timeout,'cancel');

        //expect(timeout.cancel).not.toHaveBeenCalled();
    }));
});

My Code :

angular.module('timeoutUnitTest').service('MyService',function($q,$timeout){
   function _getPrivateData(timeoutPeriod,id){
      if(timeoutPeriod && timeoutPeriod){
        $timeout(function(){
          console.log('in timeout task');
        },timeoutPeriod);
      }
      var def = $q.defer(); def.resolve('1');
      return def.promise;
   }

   function test(){
     var def = $q.defer();
     return def.promise;
   }

   function getData(id,timeoutPeriod){
    return test().then(_getPrivateData.bind(null,timeoutPeriod)).then(function(){
         return 2;
      });
   }

   return {
     getData : getData
   }

});

In above I am setting a timout task only of I pass timeout parameter to getData. According to my understanding :
1) When I pass timeout argument and call flush function also with some timeout parameter -
Expectation : test should succeed and timeout should flush the set task
Actual : as per expectation

2) When I pass timeout argument and call the flush without some timeout -
Expectation : test should fail and timeout should throw error as the task is not set yet by the time flush is called. the reason for sending the timeout to flush itself. Actual : as per expectation

3) When I don't pass timeout argument and call flush function also with some timeout parameter - Expectation : test should fail and flush should throw the error as there is no timeout task set at all as timeout argument is undefined to getData Actual : not per expectation and flush succeeds.

So Why the third test fails and flush doesn't throw the error? In my real code flush always succeeds even when I don't send timeout parameter to getData and to flush as well. That is not correct.

Any help to understand the behavior of flush would be really helpful. Also main question is again how to write test to make sure timeout is not setting the task and it is settting a task?

Aucun commentaire:

Enregistrer un commentaire