vendredi 27 novembre 2015

Missing compiled element contents when unit testing ngView

After reading the angular ngViewSpec.js file, I've finally figured how to test my controller with routes, controllerAs and forms. Here is my unit test:

describe("mainControllerSpec", function() {

    var element;
    beforeEach(module("nisArch"));
    beforeEach(module("ngRoute"));

    it("clickSearch should change location with limitResults true", function () {
        var path, search;
        var ctrl;

        module(function () {
            return function ($rootScope, $compile) {
                element = $compile("<div ng-view></div>")($rootScope);
            };
        });

        module(function ($compileProvider, $routeProvider) {
            $routeProvider.when("/", {
                title: "Home",
                controller: getController,
                controllerAs: "vm",
                templateUrl: "templates/mainView.html"
            });
        });

        inject(function ($location, $controller, $rootScope, $route, $templateCache) {
            ctrl = $controller("mainController", { $location: $location });
            $location.path("/");
            $rootScope.$digest();
            ctrl.queryString = "AS65402";
            ctrl.clickSearch();
            path = $location.path();
            search = $location.search();
            expect(path).toEqual("/Search");
            expect(search).toEqual({ q: "AS65402", limitResults: "true" });
        });

        function getController() {
            return ctrl;
        }

    });
});

If I understand correctly what's going on here: I create an element with my ng-view directive, compile it, bind it to the rootscope. I then create the route and controller. Finally I set the $location and do the main part of my unit test.

This is working fine and my test is passing. What's puzzling me is that I can't see the contents of element. I would have expected them to be the contents of templates/mainView.html after the router change and $digest(). But I get nothing. I injected $route to check $route.current.templateHtml and I injected $templateCache to check that. Both correct.

Should I not expect to find the contents using element.html()? Or have I completely misunderstood what's going on here? Thanks for any help or insight, Marcus

Aucun commentaire:

Enregistrer un commentaire