监视 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');
    });

})