Unable to get property then of undefined?

我的未来我决定 提交于 2019-12-23 02:01:37

问题


Trying to run a unit test for my angular httpbased service:

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

This is the test:

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');

});

I get an error:

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

How to fix this?

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


回答1:


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

Notice the return in sayHello function.



来源:https://stackoverflow.com/questions/31602155/unable-to-get-property-then-of-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!