我有一个在控制器中定义的方法。此方法被传递给具有隔离范围的自定义指令。我如何测试实施 $scope.search 正确吗?

自动完成Ctrl

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

模板

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

指令(摘录)

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

自动完成指令Ctrl

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

单元测试

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');
        });
    });
});

日志

TypeError: 'undefined' is not a function (evaluating '$scope.search({term: term})')
有帮助吗?

解决方案

事实证明这是一件容易的事。我只需模拟所需的方法。

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'});
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top