Angular $ q promise使用Mocha,Chai和Sinon进行单元测试 [英] Angular $q promise Unit testing using Mocha, Chai, Sinon
问题描述
我正在尝试使简单的angualr $ q promise单元测试正常工作.但是我一直在使它无法正常工作方面遇到问题. 这是我的角度文件.
I'm trying to get my simple angualr $q promise unit test to work. 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});
}]);
我正在使用Mocha,Chai和sinon进行单元测试. 这是我的测试文件.
I'm using Mocha, Chai and sinon for the unit testing. 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!
推荐答案
第一个命题
您可以使用mocha的回调函数来测试异步代码以及有角的$ timeout.flush( )
You can use mocha's callback function to test asynchronous code along with the angular $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并返回承诺.您的代码应如下所示
You can use https://github.com/domenic/chai-as-promised and return a promise. Your code should look as below
it('should increment the input if number given', function() {
return $scope.addOne(1).should.eventually.equal(2);
});
这篇关于Angular $ q promise使用Mocha,Chai和Sinon进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!