【问题标题】:Simulating Enter Key Press on Input in Karma/Jasmine Tests在 Karma/Jasmine 测试中模拟输入上的 Enter 键
【发布时间】:2016-08-11 01:13:06
【问题描述】:

我正在尝试在 Angular 自定义组件中测试用户搜索功能。我尝试向其中添加文本并触发搜索的指令模板中的输入(也是唯一输入)是:

 <input type="text" ng-model="searchInput" class="form-control search"/>

我想在上面的输入中添加一个文本值“用户”。测试以确保它具有该值,然后模拟回车键以选择第一个匹配节点。

  1. 获取输入元素
  2. 在输入中添加文本
  3. 测试以确保输入值正确
  4. 输入时按回车
  5. 文本以确保搜索中的第一个匹配项是正确的

试过了:

   it ("should search for the specified node", function () {
              var value = "User is not registered"

               var input = diagramDirective.find("input");

               $(input).val(value).trigger("input");
               scope.$apply();

               //why can't I trigger a click event here by doing something like
               var e = jQuery.Event("keypress");
               e.keyCode = 13;

               $(input).trigger(e);


    }

谢谢

【问题讨论】:

  • 单元测试用于测试组件的 API。通过端到端测试来测试 UI ~ protractortest.org/#
  • 谢谢菲尔,我知道量角器也是一个很好的工具。我很好奇为什么我不能像上面那样做一些事情。我根据我最近的尝试添加了一些代码。

标签: javascript jquery angularjs d3.js karma-jasmine


【解决方案1】:

您需要将您的 JQuery.Event 与触发控制器中最终搜索的任何内容相匹配,因此如果您的控制器正在侦听按键,那么您需要确保您的 jQuery.Event 是一个“按键”事件,但是如果您的控制器正在侦听“keyup”,您需要将 jQuery 事件设置为“keyup”。还需要在实际事件的回调中寻找匹配项

  it("should search for the specified nodes", function () {
            var value = "User is not registered";
            var e = jQuery.Event("keypress");
            e.keyCode = 13;

            // find the input
            var directiveElementInput = diagramDirective.find("input");

            // Set some text!
            $(directiveElementInput).val(value).trigger("input");

            // make sure the input has the value
            expect(directiveElementInput).toHaveValue(value);

            // execute the event on the input and check for the selected item
            $(directiveElementInput).keypress(function () {
                // do your check here for the matching item here
            }).trigger(e);
        });

【讨论】:

    【解决方案2】:

    我建议查看输入框上的事件侦听器,因为输入框不一定总是由“输入”键触发。它可能正在侦听的其他一些可能事件是“blur”、“keyup”、“change”。根据它是事件侦听器还是 on-whatever 事件,您必须相应地触发它。

    对不起,这有点含糊,但如果不知道附加到输入框的事件侦听器,就很难说。

    希望这有帮助!

    【讨论】:

      猜你喜欢
      • 2017-04-29
      • 1970-01-01
      • 1970-01-01
      • 2016-01-26
      • 2014-05-17
      • 1970-01-01
      • 1970-01-01
      • 2018-05-10
      • 2013-10-27
      相关资源
      最近更新 更多