Angular, 否则, 承诺

Angular, Sinon, promises

无法理解 angular,sinon 和 promises。如果我需要测试这样的东西:

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 承诺的解决方式?

您可以将 locations 作为已解决的承诺值传递给间谍 $q.when:

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

它应该可以正常工作。它在您的情况下不起作用的原因是因为您正在从延迟对象创建承诺并且从未用适当的值解析它。

when(value); Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.