javascript - Testng a partally executed $timeout in AngularJS -


i have angularjs service. service uses $timeout in function. i'm trying figure out how test service in various situations. here code:

myapp.factory('myservice', ['$timeout', function($timeout) {   var isrunning = false;   var mytimer = null;    return {     mytimer: mytimer,     isrunning: isrunning,      execute: function(time) {       this.isrunning = true;       this.mytimer = $timeout(         function() {           this.isrunning= false;           this.mytimer= null;         },         time       );                     }   }; }]); 

now, i'm trying test code. have following written:

describe('myservice', function () {   var myservice = null;   var $timeout = null;   var $rootscope = null;    beforeeach(inject(function (_$timeout_, _$rootscope_, _myservice_) {     myservice = _myservice_;     $timeout = _$timeout_;     $rootscope = _$rootscope_;   }));    it('should run 1 second', function() {     myservice.execute(1000);     $timeout.flush();     $rootscope.$digest();      expect(myservice.isrunning).tobe(false);   }); }); 

the test "works". however, if 750 milliseonds have elapsed, expect myservice.isrunning true. however, not know how test scenario. can please show me how test tht situation? thank you

you can imitate amount of time passing $timeout.flush method. method takes optional parameter called delay. it's explained in documentation here. in mind, write test looks this:

it('should run 1 second', function() {   myservice.execute(1000);   $timeout.flush(750);   $rootscope.$digest();    expect(myservice.isrunning).tobe(true); }); 

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -