samedi 4 juillet 2015

Unit testing angular directive replaced by textarea

Hi I have this directive definition which is replaced by a textarea. It looks something like this:

angular.module('xyz')
.directive('dir1', [function()
{
    return {
        scope : {},
        replace : true,
        template : "<textarea></textarea>",
        require : "ngModel",
        link : function(scope, element, attrs, ctrl)
        {
            ctrl.$parsers.push(function(value)
            {
                //..do some stuff
                return value;
            });
        }
    }
}]);

Now the problem is that I can't really test the branch inside the ctrl.$parsers. I tried so many different things. It is easy when it is a form so I just do something like scope.input_form.input_value.$setViewValue('abcd') and the model gets updated and so on. This case is just really difficult to reach the $parsers. The bit that is //..do some stuff is quite long and has a few corner cases and it is not feasible to test it via trial and error. Can anyone help? I will provide more details if this isn't clear.

UPDATE:

So the unit test is something like this:

describe('Specs for dir1', function()
{
    var scope, dir_1;
    beforeEach(module('xyz'));
    beforeEach(inject(function($compile, $rootScope)
    {
         scope = $rootScope.$new();
         scope.test_data = "";
         dir_1 = $compile("<dir1 ng-model='test_data'></dir1>")(scope);
    }));

    it('Does some stuff in $parsers when view value changes', function()
    {
        //I want to do something like this:
        //<textarea>.setViewValue("some value") which will
        //call one of the functions injected in $parsers.
    });
});

BTW you can be rest assured that the function injected in $parsers does get invoked when I try it out in the browser i.e. on rendered html when I type something into the textarea.

Aucun commentaire:

Enregistrer un commentaire