jeudi 2 juin 2016

Problems testing $http.get when returning json data with Jasmine and AngularJs

I've struggling the whole day already figuring out how to test the result of a $http.GET request which is returning data from a .json file. I hope any of you can be of any help here.. Practical the app is running perfectly and is returning the correct json I expected.

I have a controller named 'ProgramController' and a service ; 'DataService'.

Controller:

function ProgramController(DataService) {
    var vm = this;
    vm.timeline = {};

    activate();

    ////////////////
    function activate() {
        DataService.getTimelineData().then(function (data) {
            console.log(data);
        });
    }
}

Service:

function DataService($http) {
    var service = {
        getTimelineData: getTimelineData
    };

    return service;

    ///////////////
    function getTimelineData() {
        return $http.get('data/program.json').then(function (httpResult) {
            return httpResult.data;
        });
    }
}

Tests for testing the controller and service response;

describe('Program', function () {

var controller, scope, dataserviceMock, httpBackend;

beforeEach(module('mymodule'));

beforeEach(inject(function ($rootScope, $controller, $injector, $q, $httpBackend, $http) {
    scope = $rootScope.$new();
    httpBackend = $httpBackend;

    dataserviceMock = {
        getTimelineData: function () {
            return $http.get('data/program.json').then(function (httpResult) {
                return httpResult.data;
            });
        }
    };

    controller = $controller('ProgramController', { 'DataService': dataserviceMock });
}));

describe('when initializing the controller', function () {
    it('object timeline should be something', function () {
        httpBackend.whenGET('data/program.json').respond(mockedTimelineData);
        httpBackend.flush();
        expect(controller.timeline).toEqual(mockedTimelineData);
    });
});

});

The test is failing when I try this out. Although the 'controller.timeline' property is defined as '{}' in the controller. The spec doesn't even get to that point.. It fails on the .flush() of the httpBackend.

The result in the brower show the following error;

Error: Unexpected request: GET js/app/program/program.template.html

No more request expected

Which references to the template which belongs with the ProgramController defined at the $stateProvider definition.

Do any of you have an idea what i'm doing wrong here? I really have no clue. I've already done some stuff with $q.defer and promise resolving in tests, but I really can't get my head around this...

Aucun commentaire:

Enregistrer un commentaire