如何测试从$ http异步加载JSON的角度服务

时间:2016-01-05 02:56:12

标签: angularjs jasmine

角度单位测试还是新手。我在模块'example'中有一个服务,它通过$ http服务加载一个本地JSON文件,并异步返回响应数据。

我发现我需要测试(使用Jasmine)

  • http GET连接本地资源
  • http服务加载JSON并获取正确的json内容
  • 该服务履行了其返回响应数据的承诺

我的服务代码

  /**
   * Service to load JSON data.
   */
  .service('jsonLoader', ['$http','$timeout', 'TABLE_DATA_LOC', function($http, $timeout, TABLE_DATA_LOC) {
    this.load = function() {
      return $timeout(function() {
        return $http.get(TABLE_DATA_LOC).then(function(response) {
          return response.data;
        });
      }, 30);
    };

我目前的测试内容:

describe('jsonLoader service', function() {

  var jsonLoader, httpBackend;

  beforeEach(module("example"));

  beforeEach(inject(function(_jsonLoader_, $httpBackend) {
    jsonLoader = _jsonLoader_;
    httpBackend = $httpBackend;
  }));

  it("should load json", function() {
    httpBackend.whenGET('./mock/sample.json').respond({
        "people": [
          {
            "person": {
              "firstName": "jim",
              "lastName": "bob"
            }
          }
        ]
      });
  });
});

是第一部分,我将如何使用jasmine来测试异步承诺?

1 个答案:

答案 0 :(得分:1)

继续我的评论之后,我将采用这种方法。

describe('jsonLoader service', function() {
    var uri;

    beforeEach(module('example', function($provide) {
        $provide.constant('TABLE_DATA_LOC', uri = 'mock/sample.json');
    }));

    it('should load JSON in a $timeout and return the response data', inject(function($httpBackend, $timeout, jsonLoader) {
        var responseData = 'whatever', resolved = false;

        $httpBackend.expectGET(uri).respond(responseData);

        jsonLoader.load().then(function(data) {
            expect(data).toBe(responseData);
            resolved = true;
        });

        $timeout.flush();
        $timeout.verifyNoPendingTasks();

        expect(resolved).toBeFalsy();

        $httpBackend.flush();
        $httpBackend.verifyNoOutstandingRequest();

        expect(resolved).toBeTruthy();
    }));
});

Plunker demo〜http://plnkr.co/edit/jmc9FWjbOkpmT6Lu8kVn?p=preview

相关问题