2016-10-09 198 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)的参数,此测试将始终返回成功,我认为测试的目的是显示像这样的错误。你有什么看法? –