为什么我得到'无法获得属性'然后'未定义或空引用'?

时间:2015-07-24 07:26:19

标签: angularjs unit-testing jasmine

我写了一个角度服务:

app.factory('newService', function($http, $q) {
  return {
    getCustomer: function(id) {
      var deferred = $q.defer();
      $http.get('/api/customers?id=' + id).success(function(data) {
        deferred.resolve({
          id: 1,
          name: 'Bert'
        });
      }).error(function(err, msg) {
        deferred.reject(msg);
        $log(err);
      });
      return deferred.promise;
    }
  };
});

我的测试看起来像这样:

it('should call service', function() {
    $scope.test2();
    expect(myMock.getCustomer).toHaveBeenCalledWith(2);
});

但是我收到了错误:

TypeError: Unable to get property 'then' of undefined or null reference

plunkr:http://plnkr.co/edit/PHIklcth6uqyYJFcaoLU?p=preview

2 个答案:

答案 0 :(得分:0)

您正在不必要地使用defer。当你返回它时,它还没有解决,因为它在http promise中设置。将您的getCustomer更改为

getCustomer: function(id) {
  return $http.get('/api/customers?id=' + id).success(function(data) {
    return {
      id: 1,
      name: 'Bert'
    };
  }).error(function(err, msg) {
    $log(err);
    return msg;

  });
}

答案 1 :(得分:0)

您已使用方法newService创建了模拟getCustomer,但这只是一种假方法。它没有then()函数,因此当JS试图在您对$scope.test2()的调用中找到它时会抛出错误。

你也必须模仿这个功能。

此外,您应该重构您的服务,因为您$q的使用是多余的,因为$http.get()已经返回了一个承诺。

app.factory('newService', function($http) {

  return {

    getCustomer: function(id) {

      return $http
        .get('/api/customers?id=' + id)
        .then(function(data){
          return {
            id: 1,
            name: 'Bert'
          };
        })
        .catch(function(err) {
          $log(err);
        });
    }

  };

});