I have an AngularJs controller that calls its own refresh() method while it is being constructed. The method in question accesses some template elements that are not present during unit testing.

function ListController($scope) {
    /// ...

    $scope.refresh = function() {
        var tabId = angular.element('#id li.active a').attr('href');
        //etc
    }

    //Initialise
    $scope.refresh();
}

The refresh method causes unit tests to fail while the controller is being constructed. As the work it does is irrelevant to the tests, I want to override the method with a stub and simply test that it has been called.

Jasmine's Spy functionality looks like the way to go, but I can't find a way of setting one up for an object before it is constructed. How would I do this?

有帮助吗?

解决方案

You should move this to a directive's link function. A link function is basically the result of a compile so Then you will know for sure that your element is compiled and ready, and that will make your "refresh" function unnecessary. In general, you should never access DOM via jqLite or jQuery from the controller. Also, the link function provides direct access to element, scope, and attributes (even href) which is nice.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top