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

AngularJS - $httpBackend cannot read nested JSON property

我正在尝试通过 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;
        });
}

A GET 请求 到 URL “http://example.com/data” returns 以下数据:

{
  "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();
    });

一旦服务功能(我想测试)returns 嵌套 JSON 属性 而不是整个,我就无法以某种方式测试 http GET 请求JSON.

提前致谢!

API 响应的数据应该是正确格式的模拟数据,这里 getData 是期望对象格式的方法,因此 return 用户可以使用它。喜欢 response.data.example.user

代码

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