0

Cette spécification passe, même si elle semble devoir échouer. (Le code est d'un livre sur des rails angulaires et)

ici est l'application angulaire:

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

app.controller("CustomerSearchController", 
    ["$scope", "$http", function($scope, $http) { 
    var page = 0; 
    $scope.customers = []; 
    $scope.search = function (searchTerm) { 
     if (searchTerm.length < 3) { 
     return; 
     } 
     $http.get("/customers.json", 
     { "params": { "keywords": searchTerm, "page": page } } 
    ).then(function(response) { 
      $scope.customers = response.data; 
     },function(response) { 
      alert("There was a problem: " + response.status); 
     } 
    ); 
    }; 
    } 
]); 

et, voici la spécification Jasmine:

describe("Error Handling", function() { 
    var scope = null, 
    controller = null, 
    httpBackend = null; 
    beforeEach(module("customers")); 
    beforeEach(inject(function ($controller, $rootScope, $httpBackend) { 
    scope = $rootScope.$new(); 
    httpBackend = $httpBackend; 
    controller = $controller("CustomerSearchController", { 
     $scope: scope 
    }); 
    })); 
    beforeEach(function() { 
    httpBackend.when('GET', '/customers.json?keywords=bob&page=0').respond(500, 'Internal Server Error'); 
    spyOn(window, "alert"); 
    }); 
    it("alerts the user on an error", function() { 
    scope.search("bob"); 
    httpBackend.flush(); 
    expect(scope.customers).toEqualData([]); 
    expect(window.alert).toHaveBeenCalledWith(
     "There was a problem: 500"); 
    }); 

}); 

Je ne comprends pas comment le contrôleur accède toujours au service $ httpBackend, injecté dans la fonction anonyme passée à injecter dans la méthode beforeEach. Le service $ scope est transmis, mais httpBackend ne l'est pas.

Répondre

0

Dans votre code:

 
app.controller("CustomerSearchController", 
    ["$scope", "$http", function($scope, $http) { 
    ... 
    }] 
) 

Vous demandez d'injecter $ angulaire le http qu'il a sur fichier dans votre contrôleur. Vous n'avez pas fourni de dérogation locale ici

 
controller = $controller("CustomerSearchController", { 
     $scope: scope 
    }); 

de sorte qu'Angular remplisse votre demande d'injection avec ce qu'elle a. Comme le dit @estus, le remplacement fourni dans ngMock est lui-même injecté avec $ httpBackend, que vous avez configuré dans votre test pour agir d'une certaine manière.