AngularJS - $ httpBackend无法读取嵌套的JSON属性

时间:2016-05-03 13:21:19

标签: angularjs json jasmine typeerror httpbackend

我正在尝试通过jasmine设置http GET请求期望,但我收到以下错误:

TypeError: Cannot read property 'user' of undefined

我想测试的服务功能如下:

function getData() {
    return $http.get('http://example.com/data')
        .then(function (response) {
            return response.data.example.user;
        });
}

网址“http://example.com/data”的 GET请求会返回以下数据:

{
  "id": "1",
  "example": {
     "user": [
       {
          "name": "John",
          "wife": [
             {
                "name": "Jane",
                "age": "27"
             }
           ]
        }
    }
}

相应的测试如下所示:

describe("Service: myService", function () {
    beforeEach(module("myApp"));

    var myService, $httpBackend;

    beforeEach(inject(function (_myService_, _$httpBackend_) {
        myService = _myService_;
        $httpBackend = _$httpBackend_;

        $httpBackend.whenGET("http://example.com/data").respond("some data");
    }));

    afterEach(function () {
        $httpBackend.verifyNoOutstandingExpectation();
        $httpBackend.verifyNoOutstandingRequest();
    });

    it("should call the correct URL", function() {
        $httpBackend.expectGET("http://example.com/data");
        myService.getData();
        $httpBackend.flush();
    });

不知何故,只要服务函数(我想测试)返回嵌套的JSON属性而不是整个JSON,我就无法测试http GET请求。

提前致谢!

1 个答案:

答案 0 :(得分:2)

API响应的数据应该是正确格式的模拟数据,此处getData是方法期望的对象格式,因此可以从中返回用户。比如response.data.example.user

<强>代码

$httpBackend.whenGET("http://example.com/data").respond({
  "id": "1",
  "example": {
     "user": [] //to keep you code working
    }
})