AngularJS $timeout function not executing in my Jasmine specs

前端 未结 3 1477
醉话见心
醉话见心 2021-02-06 21:42

I\'m trying to test my AngularJS controller with Jasmine, using Karma. But a $timeout which works well in real-life, crashes my tests.

Controller:



        
3条回答
  •  独厮守ぢ
    2021-02-06 22:24

    According to the Angular JS documentation for $timeout, you can use $timeout.flush() to synchronously flush the queue of deferred functions.

    Try updating your test to this:

    it('should do stuff', function() {
      expect($scope.stuffDone).toBeFalsy();
      $scope.doStuff();
      expect($scope.stuffDone).toBeFalsy();
      $timeout.flush();
      expect($scope.stuffDone).toBeTruthy();
    });
    

    Here is a plunker showing both your original test failing and the new test passing.

提交回复
热议问题