2016-02-15 86 views
0

我試圖讓我的簡單的angualr $ q承諾單元測試工作。但是我一直在解決它的問題。 這是我的角度文件。

app.controller('theCtrl', ['$scope', '$q', function($scope, $q) { 
    $scope.addOne = function(num) { 
     var q = $q.defer(); 
     if(angular.isNumber(num)) { 
      q.resolve(num+1); 
     } else { 
      q.reject('NaN'); 
     } 
     return q.promise; 
    } 

    $scope.myVal = 0; 
    $scope.promise = $scope.addOne($scope.myVal); 

    // $scope.promise.then(function(v) {$scope.myVal = v }, function(err) {$scope.myVal = err}); 

}]); 

我正在使用Mocha,Chai和sinon進行單元測試。 這是我的測試文件。

describe("Contacts App", function() { 
    describe("the contact service", function(){ 
     var $scope, theCtrl, $q; 

     beforeEach(module('Contacts')); 

     beforeEach(inject(function($injector) { 
      var $rootScope = $injector.get('$rootScope'); 
      var $controller = $injector.get('$controller'); 
      $scope = $rootScope.$new(); 
      theCtrl = $controller('theCtrl', {$scope: $scope}); 
      $q = $injector.get('$q');  

     })); 

     it('should have a properly working promise', function() { 
      // Any answers? 
     }); 
    }); 
}); 

任何建議將非常感激。謝謝,乾杯!

回答

2

第一個命題

你可以用摩卡的回調函數來測試asynchronous code與角$ timeout.flush()

it('should have a properly working promise', function(done) { 
    expect($scope.promise).to.be.defined; 
    $scope.promise.then(function() { 
     done(); 
    }); 
    $timeout.flush(); 
}); 

第二個命題(由摩卡推薦)

沿

您可以使用https://github.com/domenic/chai-as-promised並返回承諾。您的代碼應如下所示

it('should increment the input if number given', function() { 
    return $scope.addOne(1).should.eventually.equal(2); 
}); 
相關問題