How to unit test $http in angularjs and Jasmine

て烟熏妆下的殇ゞ 提交于 2019-12-01 12:10:09

问题


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

 describe("create", function(){
        it("Should be defined", function(){
            expect(BaseService.create).toBeDefined();
        });

        it("it should POST to http://api.test.com/TEST/", function(){

          /***
           * 
           * NOT TO SURE WHAT TO DO HERE
           * 
           */

        })
    });

http://plnkr.co/edit/s8P2XlkfR6HfGuj8WIcb

I am new to Unit Testing so I am having a bit of trouble working out how to assert the following:

  1. If the method is going to x url
  2. If the method is using x method (e.g. GET, PUT, POST or DELETE)
  3. If the data passed to the method is the same as the data that is sent in the call
  4. If the return type of the method is a Promise
  5. If the contents of the Promise matches the expected type.

On a side note I am also open to suggestions for things I should also test.


回答1:


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();

   });


});


来源:https://stackoverflow.com/questions/31108273/how-to-unit-test-http-in-angularjs-and-jasmine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!