mardi 6 octobre 2015

Unit testing Angular directive, controller runs twice, first time with wrong scope

This is a weird one.

I have a directive that basically looks like this:

    function Toolbar() {
    return {
        scope:{
            resultType: '=',              
        },
        restrict: 'E',
        bindToController: true,
        controller: 'ToolbarController',
        controllerAs: 'toolbar',
        templateUrl: 'toolbar.html'
    };
}

I have a controller that looks like this:

function ToolbarController($scope, $stateParams) {
    var that = this;
    that.key = $stateParams.key;

    switch (that.resultType){
        case 'r':
            that.flag = false;
            break;
        default :
            vm.flag = true;
            break;
    }
 }

I have a test that looks like this:

it('should show the the correct flag', function() {
        scope = $rootScope.$new();
        scope.resultType = 'r';
        toolbarController = $controller('ToolbarController', {$scope: scope, 
    $stateParams: $stateParams});
            expect(toolbarController.flag).toBe(false);
        });

When I just the test the controller seems to execute twice. The first time my response type is undefined and my test fails. The second time it's right, but by then the test has already failed.

Anybody seen this before and know what the problem is?

Thanks, James

Aucun commentaire:

Enregistrer un commentaire