Search code examples
angularjskarma-runnerhttpbackend

whenDELETE : undefined is not a function


Here is what I am doing :

controller.js

 var app = angular.module('app', [ 'angularFileUpload' ]);

 app.controller('MyCtrl', [ '$scope', '$http', '$timeout', '$upload',
            function($scope, $http, $timeout, $upload) {
   $scope.something;
   $scope.deleteFile = function(fileId) {

    $http({
       method : 'DELETE',
       url : "http://xxx.xxx.xx.xx:8080/fileId
    }).success(function(response) {
        scope.something=response;
        console.log(response);
     });
 });

controllerspec.js

ddescribe("MyCtrl test cases ",function(){
    var scope , controller ,httpBackend;
    beforeEach(angular.mock.module('app'));

    beforeEach(angular.mock.inject(function($rootScope,$controller,$http, $timeout, $upload){
     scope = $rootScope.$new();
     httpBackend = $http;
    $controller('MyCtrl',{
       $scope:scope,
       $http:httpBackend,
       $timeout:$timeout,
       $upload:$upload
    });

   }));

    it("should delete selected file ",function(){
     /*HERE*/ httpBackend.when('DELETE','http://xxx.xxx.xx.xx:8080/1').respond
      ({
           "deleted"
       });
       httpBackend.flush();

       scope.deleteFile(1);

       expect(scope.something).toBeDefined();


});

I get TypeError: Undefined is not a function at line "HERE".

What am I missing ?


Solution

  • You have error in your code because of following piece of code Instead of

    beforeEach(angular.mock.inject(function($rootScope,$controller,$http, $timeout, $upload){
     scope = $rootScope.$new();
     httpBackend = $http;
    $controller('MyCtrl',{
       $scope:scope,
       $http:httpBackend,
       $timeout:$timeout,
       $upload:$upload
    });
    

    use

    beforeEach(angular.mock.inject(function($rootScope,$controller,$httpBackend, $timeout, $upload){
         scope = $rootScope.$new();
         httpBackend = $httpBackend;
        $controller('MyCtrl',{
           $scope:scope,
           $timeout:$timeout,
           $upload:$upload
        });
    

    $httpBackend is used for mocking http requests, no need to inject it inside controller, instead you may inject $http service. Also you had error as you didn't injected httpBackend service and were trying to use its function that why you got undefined error.