Question

J'ai une méthode qui est définie dans un contrôleur.Cette méthode est transmise à une directive personnalisée qui a une portée isolée.Comment tester la mise en œuvre de $scope.search correctement?

Saisie semi-autoCtrl

$scope.query = function (term) {
    // some async stuff
};

Modèle

<div ng-controller="AutocompleteCtrl">
    <div typeahead data-search="query(term)"></div>
</div>

Directive (extrait)

return {
    controller: 'AutocompleteDirectiveCtrl',
    scope: {
        search: '&'
    }
}

AutocompleteDirectiveCtrl

$scope.query = function (term) {
    if (term.length > ($scope.minChars - 1)) {
        $scope.search({term: term});
    }
};

Test de l'unité

describe('Autocomplete AutocompleteDirectiveCtrl', function () {
    var $scope, $window;

    beforeEach(module('myApp'));

    beforeEach(module(function ($provide) {
        $window = {
            location: {},
            document: window.document
        };

        // We register our new $window instead of the old
        $provide.constant('$window', $window);
    }));

    beforeEach(inject(function ($rootScope, $controller) {
        $scope = $rootScope.$new();
        $controller('AutocompleteDirectiveCtrl', {$scope: $scope});
    }));


    describe('Ducktyping', function () {
        it('should contain a submit method', function () {
            expect($scope.submit).toBeDefined();
        });
    });

    describe('Controller Functionality', function () {
        it('should return false if a submit request has no term set', function () {
            expect($scope.submit()).toEqual(false);
        });
        it('should redirect to search-results page if a term is present', function () {
            $scope.action = 'search-results.html';
            $scope.submit('mySearchTerm');
            expect($window.location.href).toBe('search-results.html/products/mySearchTerm');
        });
        it('should do a searchquery if term length is equal or longer then min-chars', function () {
            $scope.minChars = 3;
            $scope.query('myTerm');
        });
    });
});

Enregistrer

TypeError: 'undefined' is not a function (evaluating '$scope.search({term: term})')
Était-ce utile?

La solution

Il s’avère que c’était facile.Je n'avais qu'à me moquer d'une méthode requise.

it('should do a searchquery if term length is equal or bigger then min-chars', function () {
    $scope.minChars = 3;
    $scope.search = function (term) {
        return term;
    };
    spyOn($scope, 'search');
    $scope.query('bes');
    expect($scope.search).toHaveBeenCalledWith({term: 'bes'});
});
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top