【问题标题】:AngularJS - $httpBackend cannot read nested JSON propertyAngularJS - $httpBackend 无法读取嵌套的 JSON 属性
【发布时间】:2016-08-28 13:43:05
【问题描述】:

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

对 URL“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 请求。

提前致谢!

【问题讨论】:

    标签: angularjs json jasmine typeerror httpbackend


    【解决方案1】:

    API 响应的数据应该是正确格式的模拟数据,这里getData 是对象格式的方法,以便可以从中返回用户。喜欢response.data.example.user

    代码

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

    【讨论】:

    • 谢谢。但是如果模拟数据很长,并且 test.js 包含几个具有不同模拟数据的 http 请求测试(假设它们都是像这样大规模的:sitepoint.com/youtube-json-example)怎么办?我是否应该在单独的 JSON 文件中传输模拟,以免测试文件中的数千个模拟数据行填满?
    • 是的。您可以..或者 ypu 可以将这些数据保存在单独的 JavaScript 文件中..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多