Вопрос

I am trying to write unit tests to test my directives. However, when I invoke a click on a checkbox, it will not update the model.

How can I make it change the model? Somehow it doesn't seem to bind.

When I remove the directive, and just use a plain checkbox bound to a scope var, the same behavior as below is found. (So this is not specifically a problem for directives)

Spec function:

describe('validationGroup directive',function(){
    var elm,scope;
    beforeEach(function(){
        //Create a scope
        scope.who = {};
        scope.who.selfIncluded = true;
        scope.who.othersIncluded = false;

        //Compile basic form
        inject(function($compile) {
            elm = angular.element('<div ng-form="testFormName" validation-group="groupName">' +
                '<input id="check1" type="checkbox" atleast-one-insured ng-model="who.selfIncluded" ng-change="update()">' +
                '<input id="check2" type="checkbox" atleast-one-insured ng-model="who.othersIncluded"ng-change="update()">' +
              '</div>');
            elm = $compile(elm)(scope);
        });
        scope.$digest();
    });

    //Test the basic form we compiled
    it("Should manipulate the model",function(){
        var cb0 = elm.find("input").eq(0);
        expect(scope.who.selfIncluded).toBeTruthy(); // Succeeds
        cb0.triggerHandler('click');
        scope.$digest(); // probably not necesarry
        expect(scope.who.selfIncluded).toBeFalsy();  // Fails
    });
});
Это было полезно?

Решение

As I mentioned in the comment, angular-scenario has a utility called browserTrigger that works well for angular app testing:

browserTrigger(element,'click');

Другие советы

In your case, I think you could simply replace:

cb0.triggerHandler('click');

with:

cb0.trigger('click');

As triggerHandler does not trigger the true browser event, just executes all handlers attached to an element for an event.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top