測試angular中的service

在angularjs中,service是單例的,通常用來與後臺交互數據,需要數據的組件只需要注入某個service即可,service的典型例子:

app.factory('EventService', ['$http', '$q',
  function($http, $q) {
      return {
          getEvents: function() {
              var deferred = $q.defer();
              $http.get('/events.json').success(function(result) {
                  deferred.resolve(result);
              }).error(function(result) {
                  deferred.reject(result);
              });
              return deferred.promise;
          }
      };
  }]);

對於$http的請求,將使用$httpBackend服務進行測試並指定模擬返回的數據:

it('should have settings from http request', function() {
    var result;
    var expected = {
        "period": "day",
        "date": "2015-3-23",
    };
    //setup
    httpBackend.expectGET('/XXX.json').respond(expected);
    var promise = settingService.setting();
    promise.then(function(data) {
        result = data;
    });
    httpBackend.flush();
    expect(result).toEqual(expected);
});

當然 使用$httpBackend(http://docs.angularjs.cn/api/ngMock/service/$httpBackend)服務前需要將它注入,

beforeEach(function() {
    module('services');
    inject(function(SearchSettingService, $httpBackend) {
        settingService = SearchSettingService;
        httpBackend = $httpBackend;
    });
});

$httpBackend提供了很多方便測試的方法,並且很好地支持REST。

httpBackend.expectGET(url).respond(data);
httpBackend.expectPOST(url, param).respond(data);
httpBackend.expectJSONP(url).respond(data);

還有其他的方法請自行查詢。

還需要解釋的是:httpBackend.flush(); 當執行這行代碼時,angular會調用這個setup(發送請求並攔截該請求),並將返回指定的數據。

在前面的文章裏面我們介紹了Moco(http://hcc0926.blog.51cto.com/172833/1619706), 也可以通過Moco進行打樁測試,配置很簡單。


參考鏈接:

 

http://www.smashingmagazine.com/2014/10/07/introduction-to-unit-testing-in-angularjs/

http://fdietz.github.io/recipes-with-angular-js/consuming-external-services/testing-services.html

http://andyshora.com/unit-testing-best-practices-angularjs.html

http://nathanleclaire.com/blog/2014/04/12/unit-testing-services-in-angularjs-for-fun-and-for-profit/

http://icodeit.org/2014/01/how-to-test-service-in-angularjs/


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章