如何在angular.js控制器测试中模拟资源

时间:2015-10-19 17:26:01

标签: angularjs angularjs-service angular-promise

我有以下测试:

'use strict';

describe('cities', function() {
  beforeEach(module('myApp.cities'));

  var $controller, $q, $rootScope, $scope;

  beforeEach(inject(function(_$controller_, _$q_, _$rootScope_) {
    $controller = _$controller_;
    $q = _$q_;
    $rootScope = _$rootScope_;
    $scope = $rootScope.$new();
  }));

  describe('CitiesIndexController', function() {
    it('does', function() {

      var city = function (properties){
        for(var k in properties) 
          this[k]=properties[k];
      };
      city.index = function(){
        var deferred = $q.defer();
        deferred.resolve( {id: 1, ans:'wer'} );
        return deferred.promise;
      };

      var this_controller = $controller('CitiesIndexController', { $scope: $scope, $state: {}, City: city } );
      expect($scope.some_value).toEqual('this value');
      expect($scope.cities).toEqual({ some: 'value' });
    });
  });

});

测试以下代码:

controller('CitiesIndexController',
               [ '$scope', '$state', 'City',
        function( $scope,   $state,   City) {
            City.index({}, function(cities) {
                $scope.cities = cities;
            });
            $scope.some_value = 'this value';
        }]
    );

angular.module('myApp.cities.service', []).
    factory('City', ['$resource', 'Config', function($resource, Config) {
        var url = Config.api_endpoint + "/cities/:id.json";
        var defaults = {};
        var actions = { index: { method: 'GET', params: undefined, isArray: true, headers: undefined },
                        show:  { method: 'GET', isArray: false,
                                 url: Config.api_endpoint + "/cities/:cityname.json"
                               }
                      };
        return $resource(url, defaults, actions);
    }]);

我收到此错误:

预期未定义为等于Object({some:'value'})。

所以City.index()不会被调用?这是关于$ q或承诺构建的设置问题吗?

0 个答案:

没有答案