監視 Angular 服務

在這個例子中我們有一個服務,讓我們稱它為搜尋服務,它有一個名為 search() 的方法,它將向後端 API 發起 get 請求。

function SearchService($http) {
    const service = {};
    
    service.search = function() {
        return $http({method: 'GET', url: `/api/search`})
    }        

    return service;
}
angular.module('app').factory('searchService', SearchService);

測試

describe('search service', function() {
    var $httpBackend;
    var searchService;
    beforeEach(angular.mock.module('app'));
    
    beforeEach(inject(function(_$httpBackend_, _searchService_) {
        $httpBackend = _$httpBackend_;            
        searchService = _searchService_;
    }));

    it('should perform http call to the search api', function(){
        searchService.search();
        $httpBackend.expectGET('/api/search');
    });

})