[英]Angular $q promise Unit testing using Mocha, Chai, Sinon
I'm trying to get my simple angualr $q promise unit test to work. 我试图让我简单的angualr $ q promise单元测试正常工作。 But I've been having problems getting it to work. 但是我一直在遇到问题。 Here's my angular file. 这是我的角度文件。
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});
}]);
I'm using Mocha, Chai and sinon for the unit testing. 我正在使用Mocha,Chai和sinon进行单元测试。 Here's my test file. 这是我的测试文件。
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?
});
});
});
Any suggestion would be really appreciated. 任何建议将不胜感激。 Thanks, Cheers! 谢谢,干杯!
First proposition 第一个命题
You can use mocha's callback function to test asynchronous code along with the angular $timeout.flush() 您可以使用mocha的回调函数与$ timeout.flush()一起测试异步代码。
it('should have a properly working promise', function(done) {
expect($scope.promise).to.be.defined;
$scope.promise.then(function() {
done();
});
$timeout.flush();
});
Second proposition (recommended by Mocha) 第二个命题 (摩卡咖啡推荐)
You can use https://github.com/domenic/chai-as-promised and return a promise. 您可以使用https://github.com/domenic/chai-as-promised并返回承诺。 Your code should look as below 您的代码应如下所示
it('should increment the input if number given', function() {
return $scope.addOne(1).should.eventually.equal(2);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.