【问题标题】:Angular Unit Test - Click in directive not triggeringAngular Unit Test - 点击指令不触发
【发布时间】:2015-10-20 16:06:24
【问题描述】:

问题

我正在尝试从指令模板中单击带有value="agency"radio 输入,最终目标是更改范围变量newDatasourceType

相关来源

指令模板

  <div ng-if="!datasources" class="new-datasource">
        <input name="agencyOrWidget" type="radio" ng-model="newDatasourceType" value="agency" />
        <label>Agency</label>
        <input name="agencyOrWidget" type="radio" ng-model="newDatasourceType" value="widget" />
        <label>Widget</label>
        <select ng-if="newDatasourceType=='widget'" name="{{inputPrefix}}[0][widget_id]">
              <option>Choose a widget...</option>
              <option ng-repeat="(id, options) in widgetList" value="{{id}}">{{id}}</option>
        </select>
        <select ng-if="newDatasourceType=='agency'" name="{{inputPrefix}}[0][agency_id]">
              <option>Choose an agency...</option>            
              <option ng-repeat="(id, name) in agenciesList" value="{{id}}">{{name}}</option>
        </select>
  </div>

相关单元测试

尝试的部分和注释在 cmets 中。

it('Select Agencies', function() {
    // Running this to see if it does anything
    scope.newDatasourceType = 'agency';

    //create the element with the directive template
    elem = $compile(directive)(scope);
    scope.$digest();

    // Returns `1`
    console.log(elem.find('input[value="agency"]').length);

    // elem.find('input[value="agency"]').triggerHandler('click');
    elem.find('input[value="agency"]').click(function() {
        // Doesn't get triggered
        console.log('click');
    });

    // Didn't do anything...
    // scope.$digest();
    // scope.$apply();


    // console.log(elem.html());

    // Test items
    expect(elem.find('select option:nth-child(2)').val()).toBe(Object.keys(scope.agenciesJson)[0]);
});

我所看到的

无论我手动设置newDatasourceType 还是尝试点击它,只有Choose a widget... 的选择块可见。

【问题讨论】:

    标签: javascript jquery angularjs unit-testing


    【解决方案1】:

    除了触发click 事件之外,您还必须更改单选按钮上的checked 属性。这是一个例子http://jsfiddle.net/k1axxs21/1/

    【讨论】:

    • 效果很好。我希望我明白为什么trigger('click') 有效,但triggerHandler('click')click() 都无效。
    • 所有方法:trigger('click')triggerHandler('click')click() 应该可以工作,预计 click(function(){...}) 因为在这里您添加了一个新的处理程序而不是触发一个事件。这里的主要思想是更改 checked 属性,因为角度会在单选按钮的每个单击事件上检查它并更改模型状态 github.com/angular/angular.js/blob/master/src/ng/directive/…
    猜你喜欢
    • 1970-01-01
    • 2013-04-15
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多