javascript - 如何对依赖于 Promise 的 AngularJS Controller 进行单元测试?

标签 javascript angularjs unit-testing promise

在我的 Controller 中,我有:

  $scope.index = function() {
    CompanyService.initialized.then(function() {
      var company_id = CompanyService.getCompany()._id;
      LocationService.list(company_id, $routeParams.location_parent_id).then(function(response) {
        if(response.data.status === 'ok') {
          $scope.locations = response.data.locations;
          $scope.current_location = response.data.location || null;
        }
      });
    });
  }

所以它应该获取LocationService列表,测试如下:

it('should get locations', function() {
  $httpBackend.when('GET', '/api/v1/location/list').respond({status: 'ok', locations: ['loc1', 'loc2']})
  $scope.index();
  expect($scope.locations.length).toEqual(2);

但是,这种情况永远不会发生,因为 CompanyService 有一个永远不会在单元测试中得到解决的 promise 。如何模拟 CompanyService 返回的 promise 或绕过它?

最佳答案

使用 Jasmine 中的 createSpyObj 方法简单地模拟调用:

describe('one test', function(){

 var deferred, CompanyService, $scope;

 beforeEach(inject(function ($q, $rootScope, $controller) {
  params = {
        $scope: $rootScope.$new(),
        CompanyService = jasmine.createSpyObj('CompanyService', ['initialized'])
  }
  params.CompanyService.initialized.andCallFake(function () {
      deferred = $q.defer();
      return deferred.promise;  //will fake to return a promise, in order to reach it inside the test
    });
  $controller('YourController', params);
 });

 it('my test', function(){
     deferred.resolve({}); //empty object returned for the sample but you can set what you need to be returned
     $scope.$digest(); //important in order to resolve the promise
    //at this time, the promise is resolved! so your logic to test can be placed here
 });
});

关于javascript - 如何对依赖于 Promise 的 AngularJS Controller 进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21895684/

相关文章:

javascript - 延迟一个接一个地动画 sibling

javascript - 是否可以在悬停 div 时从 .m3u 源流式传输?

javascript - 使用时间戳和 Moment.js

javascript - 如何在网页中多次加载包含 document.write 的 Javascript?

javascript - angularJs 单选按钮不可见?

javascript - 对 StackExchange API 的 HTTP GET 请求不会在 AngularJS 应用程序中返回

Angular 中的图像作为复选框

c# - 似乎无法伪造 RNGCryptoServiceProvider

java - ActivityUnitTestCase getActionBar() 返回 null

angular - getTestBed 和 TestBed 的区别