【问题标题】:Unable to get property then of undefined?无法获得未定义的财产?
【发布时间】:2015-07-24 04:23:29
【问题描述】:

尝试为我的基于 http 的 Angular 服务运行单元测试:

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

【问题讨论】:

    标签: angularjs unit-testing jasmine


    【解决方案1】:
    return {
      sayHello:function(usr){
        return $http.get('/api/doit').then(
          function(result){
            return 'hello '+usr;
        });
      }
    }
    

    注意 sayHello 函数中的返回。

    【讨论】:

      猜你喜欢
      • 2012-12-14
      • 1970-01-01
      • 1970-01-01
      • 2020-10-18
      • 2020-11-25
      • 1970-01-01
      • 2011-03-13
      • 1970-01-01
      • 2018-04-11
      相关资源
      最近更新 更多