javascript - Capybara 测试更改脚本是否有效并将属性添加到 HTML 字段

标签 javascript ruby-on-rails rspec capybara

有一个包含多个字段的表单。我们需要对一个字段进行即时验证(电子邮件字段)。即时验证有效,但我正在努力寻找一种向其添加自动化测试的方法。

JS:

function addEvent(node, type, callback) {
  if (node.addEventListener) {
    node.addEventListener(type, function(e) {
      callback(e, e.target);
    }, false);
  } else if (node.attachEvent) {
    node.attachEvent('on' + type, function(e) {
      callback(e, e.srcElement);
    });
  }
}

 function shouldBeValidated(field) {
  return (
    !(field.getAttribute("readonly") || field.readonly) &&
    !(field.getAttribute("disabled") || field.disabled) &&
    (field.getAttribute("pattern") || field.getAttribute("required"))
  );
}

 function instantValidation(field) {
  if (shouldBeValidated(field)) {
    const invalid =
      (field.getAttribute("required") && !field.value) ||
      (field.getAttribute("pattern") && field.value && !new RegExp(field.getAttribute("pattern")).test(field.value));

     if (!invalid && field.getAttribute("aria-invalid")) {
      field.removeAttribute("aria-invalid");
    } else if (invalid && !field.getAttribute("aria-invalid")) {
      field.setAttribute("aria-invalid", "true");
    }
  }
}

 const inputToValidate = document.getElementById("contact_email_instant_validation");

 document.addEventListener('DOMContentLoaded', (event) => {
  addEvent(inputToValidate, "change", function(e, target) {
    instantValidation(target);
  });
})

HTML:

<label class="control-label email optional" for="check_sale_customer_contact_email">Contact email</label>
<input
  aria-required="true"
  id="contact_email_instant_validation"
  class="form-control string tel optional"
  name="check_sale[customer][contact_email]"
  pattern="^(([-\w\d]+)(\.[-\w\d]+)*@([-\w\d]+)(\.[-\w\d]+)*(\.([a-zA-Z]{2,5}|[\d]{1,3})){1,2})$"
  required="required"
  spellcheck="false"
  size="100"
  title="Customer contact email"
  type="email">

规范:

it "adds aria-invalid attribute" do
  fill_in("contact_email_instant_validation", with: "invalid.email")
  # Trigger the onchange evant
  page.execute_script("$('#contact_email_instant_validation').trigger('change');")
  # Expect html aria-invalid
  expect(page).to have_selector("input[aria-invalid='\"true\"]")
end

规范是红色的,page.execute_script 返回nil,我不明白这个东西是否可以测试。

测试日志:

12:33:08.190 INFO [ActiveSessionFactory.apply] - Capabilities are: {
  "browserName": "chrome",
  "chromeOptions": {
    "w3c": false
  },
  "cssSelectorsEnabled": true,
  "javascriptEnabled": true,
  "loggingPrefs": {
    "browser": "ALL"
  },
  "nativeEvents": false,
  "rotatable": false,
  "takesScreenshot": false,
  "version": ""
}
12:33:08.190 INFO [ActiveSessionFactory.lambda$apply$11] - Matched factory org.openqa.selenium.grid.session.remote.ServicedSession$Factory (provider: org.openqa.selenium.chrome.ChromeDriverService)
Starting ChromeDriver 75.0.3770.140 (2d9f97485c7b07dc18a74666574f19176731995c-refs/branch-heads/3770@{#1155}) on port 26448
Only local connections are allowed.
Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
[1563539588.250][SEVERE]: bind() failed: Cannot assign requested address (99)
12:33:10.078 INFO [ProtocolHandshake.createSession] - Detected dialect: OSS
12:33:10.263 INFO [RemoteSession$Factory.lambda$performHandshake$0] - Started new session c4e2161e818136d450f5a2cba943cd72 (org.openqa.selenium.chrome.ChromeDriverService)
12:33:19.567 INFO [ActiveSessions$1.onStop] - Removing session c4e2161e818136d450f5a2cba943cd72 (org.openqa.selenium.chrome.ChromeDriverService)

最佳答案

您不应使用 execute_script 来触发页面上的事件。它将允许执行用户无法执行的操作,因此可能使您的测试完全无效。相反,您应该只执行用户在页面上执行的操作。

在这种情况下,您依赖于 change 事件,该事件在输入失去焦点之前不会被触发 - https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event 。有多种方法可以导致元素失去焦点(单击不同的元素等),但在这种情况下最简单的方法可能就是按 Tab 键。由于 fill_in 返回已填充的元素,因此您可以直接链接到它

fill_in("contact_email_instant_validation", with: "invalid.email").send_keys(:tab)
# Expect html aria-invalid
expect(page).to have_selector("input[aria-invalid='true']") # could probably just be simpler as "input[aria-invalid]" 

注意:我还修复了您期望的最终选择器

关于javascript - Capybara 测试更改脚本是否有效并将属性添加到 HTML 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57019468/

相关文章:

javascript - jquery多个ajax文件上传循环异步与多个进度条

Javascript trim 双斜杠

ruby-on-rails - ExtJs4 json data.store 和 Rails

ruby-on-rails - 事件管理员 : Customize only new form

ruby-on-rails - 从 STRIPE 向公众公开客户 ID 或信用卡 ID 是否安全?

ruby-on-rails - 用于请求呈现文本的 RSpec 匹配器

javascript - Sequelize.js - findAll 和 Ordering

javascript - 检查 ByClassName 时未定义的输入值

ruby-on-rails - 如何卸载rails中 "require"语句加载的文件

rspec - 如何在不启用旧语法的情况下取消 rspec 3 中的 stub ?