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

Capybara test that on change script works and adds attribute to the HTML field

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

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 returns 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] - 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[=14=]] - Started new session c4e2161e818136d450f5a2cba943cd72 (org.openqa.selenium.chrome.ChromeDriverService)
12:33:19.567 INFO [ActiveSessions.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 returns 填充的元素,您可以链接到它

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 放在测试中也是一个坏主意,它更难维护)

试试这个:

find('#contact_email_instant_validation').trigger('change')