【问题标题】:Angular $q promise Unit testing using Mocha, Chai, SinonAngular $q promise 使用 Mocha、Chai、Sinon 进行单元测试
【发布时间】:2016-05-26 22:43:13
【问题描述】:

我正在尝试让我的简单 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?
       });
    });
});

任何建议将不胜感激。谢谢,干杯!

【问题讨论】:

    标签: javascript angularjs unit-testing mocha.js chai


    【解决方案1】:

    第一个命题

    您可以使用 mocha 的回调函数来测试 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);
    });
    

    【讨论】:

      猜你喜欢
      • 2015-05-16
      • 2015-12-01
      • 2021-09-27
      • 2015-10-01
      • 2023-04-11
      • 2019-02-14
      • 1970-01-01
      • 2019-02-03
      • 2018-11-05
      相关资源
      最近更新 更多