2016-10-09 200 views
0

我是新茉莉花測試,在這裏我想測試我的$資源,在工廠, 所以我第一此工廠:茉莉花單元測試工廠

angular.module('starter.services', []) 
 
    .factory('API', function($rootScope, $resource) { 
 
    var base = "http://192.168.178.40:8000/api"; 
 
    return { 
 
     getGuestListForH: $resource(base + '/guests/:id/:wlist', { 
 
     id: '@id', 
 
     wlist: '@wlist' 
 
     }) 
 
    } 
 
    });

和我測試:

beforeEach(module('starter.services')); 
 
describe('service: API resource', function() { 
 
    var $scope = null; 
 
    var API = null; 
 
    var $httpBackend = null; 
 

 
    beforeEach(inject(function($rootScope, _API_, _$httpBackend_) { 
 
    $scope = $rootScope.$new(); 
 
    API = _API_; 
 
    $httpBackend = _$httpBackend_; 
 
    $httpBackend.whenGET('http://192.168.178.40:8000/api/guests').respond([{ 
 
     id: 1, 
 
     name: 'a' 
 
    }, { 
 
     id: 2, 
 
     name: 'b' 
 
    }]); 
 
    })); 
 
    afterEach(function() { 
 
    $httpBackend.verifyNoOutstandingExpectation(); 
 
    $httpBackend.verifyNoOutstandingRequest(); 
 
    }); 
 
    it('expect all resource in API to br defined', function() { 
 
    $httpBackend.expect('http://192.168.178.40:8000/api/guests'); 
 

 
    var dd = API.getGuestListForH.query(); 
 
    expect(dd.length).toEqual(2); 
 

 
    expect(API.getGuestListForH).toHaveBeenCalled(); 
 

 
    }); 
 
});

和我的結果了:

  • 預計0至2等於
    • 預計間諜,但有功能 。我想測試的資源在工廠裏有什麼錯什麼是最好的方式來做到這一點?!

回答

0

你的測試可以做,即使沒有$rootScope和你所做的一切其他變量聲明。

而且由於您正在編寫服務方法的測試,而不是,所以您應該調用它並期望結果是某種東西。

事情是這樣的:

describe('Service: starter.services', function() { 
    beforeEach(module('starter.services')); 
    describe('service: API resource', function() { 
     beforeEach(inject(function(_API_, _$httpBackend_) { 
      API = _API_; 
      $httpBackend = _$httpBackend_; 

      $httpBackend.whenGET('http://192.168.178.40:8000/api/guests').respond([{ 
       id: 1, 
       name: 'a' 
      }, { 
       id: 2, 
       name: 'b' 
      }]); 
     })); 

     afterEach(function() { 
      $httpBackend.verifyNoOutstandingExpectation(); 
      $httpBackend.verifyNoOutstandingRequest(); 
     }); 

     it('expect all resource in API to br defined', function() { 
      var dd = API.getGuestListForH.query(); 
      $httpBackend.flush(); 
      expect(dd.length).toEqual(2); 
     }); 
    }); 
}); 

希望這有助於。

+0

非常感謝您的答覆,您的解決方案的工作,但如果我意外刪除服務模塊中的資源(id,wlist)的參數,此測試將始終返回成功,我認爲測試的目的是顯示像這樣的錯誤。你有什麼看法? –