【问题标题】:AngularJS Unit testing a link in a directiveAngularJS单元测试指令中的链接
【发布时间】:2014-05-23 22:47:41
【问题描述】:

我正在尝试编写单元测试来测试我的指令。但是,当我单击复选框时,它不会更新模型。

我怎样才能让它改变模型?不知何故,它似​​乎没有绑定。

当我删除指令并仅使用绑定到范围变量的普通复选框时,会发现与以下相同的行为。 (所以这不是指令的具体问题)

规格功能:

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
    });
});

【问题讨论】:

  • 嗯,我不能说点击不起作用,但您似乎在这里测试角核心功能。点击触发 ng-change,但这与您的应用程序逻辑无关,您不必再次测试。
  • 除此之外,还有一个名为 browserTrigger 的实用程序内置在 angular.js 中,它可以模拟事件。你试过吗?
  • 指令(代码未在此处发布)中发生了我想要测试的东西。在那段代码正常工作之前,至少基础应该按预期运行。
  • @Narretz browserTrigger 是 angular-scenario.js 的一部分,我只是尝试使用它,它可以工作!谢谢人:)您可能想将其发布为其他阅读此问答的人的可读性答案

标签: angularjs unit-testing angularjs-directive angularjs-scope karma-jasmine


【解决方案1】:

正如我在评论中提到的,angular-scenario 有一个名为 browserTrigger 的实用程序,它非常适合 Angular 应用程序测试:

browserTrigger(element,'click');

【讨论】:

    【解决方案2】:

    在你的情况下,我认为你可以简单地替换:

    cb0.triggerHandler('click');
    

    与:

    cb0.trigger('click');
    

    由于triggerHandler 不会触发真正的浏览器事件,只是执行附加到事件元素的所有处理程序

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-06
      • 1970-01-01
      • 2014-02-06
      • 2014-07-12
      • 2015-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多