How to unit test $http in angularjs and Jasmine

后端 未结 1 1063
不思量自难忘°
不思量自难忘° 2021-01-16 20:02

Here is my code, I\'ve made a Plunker as the code is long:

 describe(\"create\", function(){
        it(\"Should be defined\", function(){
            expec         


        
相关标签:
1条回答
  • 2021-01-16 20:11

    You can use httpBackend mock service that will help to test your $http.

    describe('Myctrl', function() {
    
       var $httpBackend, scope, createController, authRequestHandler;
    
       // Set up the module
       beforeEach(module('MyApp'));
    
       beforeEach(inject(function($injector) {
    
         // Set up the mock http service responses
    
         $httpBackend = $injector.get('$httpBackend');
    
         // backend definition common for all tests
    
         authRequestHandler = $httpBackend.when('GET', 'service.json')
                                .respond(true);
    
         // Get hold of a scope (i.e. the root scope)
    
         $rootScope = $injector.get('$rootScope');
    
         // The $controller service is used to create instances of controllers
         var $controller = $injector.get('$controller');
    
    
         createController = function() {
    
           return $controller('MyController', {'$scope' : scope});
    
         };
    
       })
    
    );
    
    
       afterEach(function() {
    
         $httpBackend.verifyNoOutstandingExpectation();
    
         $httpBackend.verifyNoOutstandingRequest();
    
    
       });
    
       it('should fetch authentication token', function() {
    
         $httpBackend.expectGET('service.json');
    
         var controller = createController();
    
         expect(scope.names).toBe(true); 
    
         $httpBackend.flush();
    
       });
    
    
    });
    
    0 讨论(0)
提交回复
热议问题