Angular,Sinon,承诺

时间:2015-05-19 21:56:01

标签: angularjs unit-testing mocha karma-runner sinon

无法理解角度,罪恶和承诺。如果我需要测试这样的东西:

myCtrl.js

angular.module('app')
.controller('myCtrl', ($scope, dataService)=> {

   dataService.list('location').then((lst)=> {
      $scope.list = lst;
   });

});

myCtrl-spec.js

describe('testing controller', ()=> { 

   var locations = ['A','B','C'], dataService, $scope;

   beforeEach(module('app'));

   beforeEach(inject($controller, $rootScope, _dataService_, $q) => {
        dataService = _dataService_;
        $scope = $rootScope.$new();
        let lstStub = sinon.stub(dataService,'list');
        let promise = $q.defer();
        lstStub.withArgs('location').returns(promise);
   }));


   it('gets locations', ()=> {
      $controller('myCtrl', { $scope, dataService });
      $scope.$digest();
      expect($scope.list).to.be.equal(locations);
   })
}) 

我如何告诉Sinon承诺得到解决的方式?

1 个答案:

答案 0 :(得分:4)

您可以使用$q.whenlocations作为已解决的承诺值传递给间谍:

 lstStub.withArgs('location').returns($q.when(locations));

它应该可以正常工作。它在你的情况下不起作用的原因是因为你正在从延迟对象创建一个promise并且永远不会用适当的值来解析它。

  

当(数值);   将一个可能是值的对象或(第三方)包装成$ q承诺。当您处理可能会或可能不是承诺的对象,或者承诺来自不可信任的来源时,这非常有用。