簡體   English   中英

如何測試從$ http異步加載JSON的角度服務

[英]How to test an angular service that asynchronously loads JSON from $http

角度單元測試還是相當新的。 我在模塊“ example”中有一個服務,該服務通過$ http服務加載本地JSON文件並異步返回響應數據。

我發現我需要測試(使用茉莉花)

  • 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"
            }
          }
        ]
      });
  });
});

第一部分是正確的,我將如何使用茉莉花來測試異步承諾?

根據我的評論,這是我的處理方式。

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演示〜http://plnkr.co/edit/jmc9FWjbOkpmT6Lu8kVn? p= preview

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM