dimanche 27 mars 2016

How to unit test after promise of a controller in AngularJS?

I have a controller that has a callback inside:

angular.module('controllers').controller('headerController', headerController);

function headerController(headerService) {
    var self = this;

    headerService.getHeaderContentData()
        .then(function(response) {
            self.contentData = response.content;
        });
}

My problem is that I need to check the value of contentData in an unit test. The idea is when I call expect(ctrl.contentData).to.be.defined passes the test, but the value of ctrl.contentData is undefined. Is there a way to test this behavior (test the self.contentData when the callback occurs)?

Current unit test:

describe("controller", function() {
    var controller, $httpBackend;

    beforeEach(angular.mock.inject(function($injector, _$httpBackend_){
        var $controller = $injector.get('$controller');
        $httpBackend = _$httpBackend_;

        var $scope = {};
        $httpBackend.when('GET', '/data/header.content.json')
                    .respond(require('../../mock-data/header.content.json'));
        var controller = $controller('headerController', { $scope: $scope });
        $httpBackend.flush();
    }));

    it("should have contentData property populated", function() {
        expect(controller.contentData).to.exist; // <- here fails: current value is undefined
    });
});

My unit testing framework is jasmine

Aucun commentaire:

Enregistrer un commentaire