无法获得未定义的属性?

时间:2015-07-24 04:23:29

标签: angularjs unit-testing jasmine

尝试为我的角度httpbased服务运行单元测试:

angular.module('myApp').factory('httpService',function($http)
{
  return {
    sayHello:function(usr){
      $http.get('/api/doit').then(
        function(result){
        return 'hello '+usr;
      });
    }
  }
});

这是测试:

it('should say hello from httpservice', function() {

        var returnData = 'hello Tomss';

        httpBackend.expectGET('/api/doit').respond(returnData);

        var returnedPromise = httpService.sayHello('Tom');

        var result;
        returnedPromise.then(function(response) {
          result = response;
        });

        httpBackend.flush();
        expect(result.data).toEqual('hello Tom');

});

我收到错误:

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

如何解决这个问题?

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

1 个答案:

答案 0 :(得分:2)

return {
  sayHello:function(usr){
    return $http.get('/api/doit').then(
      function(result){
        return 'hello '+usr;
    });
  }
}

注意sayHello函数的返回。