mardi 24 novembre 2015

How to test that an Angular directive runs a watch handler when its value changes

I have a directive which needs to re-evaluate when its value changes. The code is actually working fine, but I want to put in a test case to catch this and I can't seem to get the watch handler to run.

I'll provide a simplified example:

So this is the html that uses the directive - data.id is a property evaluated on the scope which could be updated and cause the directive to run its watch handler

<div my-directive="data.id"></div>

And here is the directive code

angular.module("myApp").directive("myDirective", function()
{
    return {
        restrict: "A",
        link: function(scope, element, attrs)
        {
            function execute(directiveValue) {
                /** run directive things **/
            }
            execute(attrs.myDirective);
            scope.$watch(attrs.myDirective, execute);
        }
    };
}]);

And this is the Jasmine test I am trying to get to pass - the spy is for a factory that would get called inside the execute() function and pass this new ID value along

describe("updating ID", function() {
        it("should re-evaluate directive", function() {
        scope.myID = "12345";
        element = $compile("<div my-directive='id=myID;'></div>")(scope);
        scope.$digest();

        scope.myID = "new ID";
        scope.$apply();
        var instances = spy.calls.mostRecent().args[2];

        expect(instances).toEqual(["new ID"]);
    });
});

My test fails with

    Expected [ '12345' ] to equal [ 'new ID' ].

Thanks!

Aucun commentaire:

Enregistrer un commentaire