abh*_*and 6 selenium rspec capybara
我的前端 UI 中有一个“复制链接”按钮。单击时,输入框中的 URL 将使用以下 JS 复制到用户的剪贴板:
const copyTextarea = document.querySelector("#copy-link-button");
copyTextarea.focus();
copyTextarea.select();
document.execCommand('copy');
Run Code Online (Sandbox Code Playgroud)
当我在本地试用时,此功能运行良好,因此我知道该功能本身运行正常。
但是我无法用 Capybara 测试副本。我从这篇文章中知道 Capybara 不提供剪贴板 API,但我的解决方法是 -
我的测试:
# Copy the link
page.find("#copy-link-button").click
wait_for_ajax
# Visit some other page that I know has an input/text field
visit account_settings_path
input = page.find("#user_email")
# Clear the field
fill_in("user[email]", with: "")
# Paste in the contents of the clipboard
input.base.send_keys([:control, "v"])
# Validate
expect(input.value).to eq("some value");
Run Code Online (Sandbox Code Playgroud)
但是,没有任何内容粘贴到该输入(input.value并input.text返回"")中。
这是一种有效的方法吗?这里的问题是首先复制文本还是我在粘贴数据时出错?
谢谢!
注意:由于此 Chrome 的原始发布已更改可用的权限类型。对于无头解决方案,请访问https://chromedevtools.github.io/devtools-protocol/tot/Browser/#type-PermissionType以查看当前可用的权限类型
有很多关于访问剪贴板内容的安全规则,所以试图从 Capybara 获得粘贴工作真的会令人沮丧。此外,当 ctrl/command v 作为按键发送时,大多数浏览器实际上不会做任何事情,因为它是系统触发的操作而不是浏览器。
但是,由于您只想验证复制是否有效,实际上并不需要触发粘贴,因此您只需要绕过使用剪贴板 API 的权限要求即可。如果您使用的是 Chrome(在非无头配置中 - 当前无法无头工作),您可以通过profile.content_settings.exceptions.clipboard在驱动程序注册中设置首选项来实现
Capybara.register_driver :chrome do |app|
options = Selenium::WebDriver::Chrome::Options.new
options.add_preference('profile.content_settings.exceptions.clipboard', {
'*': {'setting': 1}
})
Capybara::Selenium::Driver.new(app, browser: :chrome, options: options)
end
Run Code Online (Sandbox Code Playgroud)
如果您在无头模式下运行并在 Chrome 中使用最新的 Capybara 和 selenium,另一种选择是使用 CDP 授予权限
page.driver.browser.execute_cdp('Browser.grantPermissions', origin: page.server_url, permissions: ['clipboardRead', 'clipboardWrite'])
Run Code Online (Sandbox Code Playgroud)
一旦您获得了权限,您就可以使用它evaluate_async_script来访问剪贴板数据
clip_text = page.evaluate_async_script('navigator.clipboard.readText().then(arguments[0])')
Run Code Online (Sandbox Code Playgroud)
笔记:
base调用send_keys元素,只需在元素上调用它expect(input.value).to eq("some value")会导致片状的测试,而不是你应该使用的水豚提供的匹配像expect(page).to have_field(with: 'some value')或expect(input).to match_selector(:field, with: 'some value')| 归档时间: |
|
| 查看次数: |
2122 次 |
| 最近记录: |