jeudi 1 octobre 2015

How can I test the controller of an Angular directive?

I am having a problem testing the controller of my directive. Everywhere I search seems to show the same thing that I am doing, but when I try and call methods on my scope they don't seem to be there.

Probably I am missing something obvious, can anyone see it?

Here is a simplified example of my code:

myDirective.js

angular.module("app").directive("myDirective", function() {
    return {
        restrict: "E",
        templateUrl: "templates/my-directive.html",
        controller: function($scope) {

            $scope.myMethod = function() {
                /**....**/
            };
        }
    };
});

myDirectiveTest.js

describe("myDirective", function() {

    var scope, element;

    beforeEach(module("app"));
    // uses karma-ng-html2js-preprocessor
    beforeEach(module("templates/my-directive.html"));

    beforeEach(inject(function ($rootScope, $compile) {
        scope = $rootScope.$new();

        element = angular.element("<my-directive></my-directive>");

        $compile(element)(scope);
        scope.$digest();
    }));

    it("should have method defined", function() {
        // this fails
        expect(scope.myMethod).toBeDefined();
    });
});

Thanks! I am using Jasmine & Karma

Aucun commentaire:

Enregistrer un commentaire