jeudi 4 août 2016

Jasmine / Karma HTTP not mocked as expected (Angular Controller on REST call)

i've been searching around for the last days but i cannot get closer to the solution. I try to mock the http response requested by the angular controller.

angular controller:

myController = function ($http, appConfig) {

$http.post(appConfig.restPath+"/administration/imports", {

}).then(function(data){
    $scope.pagination = data;
    $scope.totalItems = data.data.content.length;
    $scope.totalPages = data.data.totalPages;
    $scope.pages = [];
    $scope.imports = data.data;
    for (var i = 0; i < $scope.totalPages; i++){
        $scope.pages.push(i);
    }
});
}

and the test:

describe('Controller: myController', function() {

// load the controller's module
beforeEach(module("myModule"));

var controller,
    scope, httpBackend, myPost;

// Initialize the controller and a mock scope
beforeEach(inject(function ($injector) {
    httpBackend = $injector.get('$httpBackend');
    myPost = httpBackend.whenPOST('http://localhost:9000/api/v1/administration/imports').respond({data: {content: ["a", "b"], totalPages: "1"}}, "");
    scope = $injector.get('$rootScope');
    var $controller = $injector.get('$controller');

    createController = function() {
        return $controller(myController, {'$scope' : scope });
    };

}));

afterEach(function() {
    httpBackend.verifyNoOutstandingExpectation();
    httpBackend.verifyNoOutstandingRequest();
});

it('should browse the list of imported files', function() {
    httpBackend.expectPOST('http://localhost:9000/api/v1/administration/imports');
    var controller = createController();
    httpBackend.flush();

});
});

But it seems that he wants to ask the server for the real data when i inspect the test in the chrome console (network traffic -> HTTP requests shows me, that he is requesting the server instead of loading the mocked data...), but he receives 403 (forbidden).

the error i receive by karma is the following:

TypeError: Cannot read property 'length' of undefined at myController.js:35:40

line 35 is:

 $scope.totalItems = data.data.content.length;

that makes me think that he tries to load the data from the REST service, receives 403, empty result (means data == {}) and then he tries to access on data.data.content.length which is undefined....

as you can see i did it exactly like google it recommends...

http://ift.tt/V2E0X0$httpBackend

Other examples on SO or anywhere else look quite similar. What am i doing wrong?

Aucun commentaire:

Enregistrer un commentaire