我在网页中为盲人和键盘用户设置了跳转链接,这些链接被移出视口以在视觉上隐藏它们; 当它们获得焦点时,它们会移动到视口内。
我想使用RSpec和Capybara测试这种行为,但不知何故它无法正常工作。
it 'moves the focus to the navigation when activating the corresponding link', js: true do
expect(page).not_to have_css '#main:focus'
page.evaluate_script "$('#jump_to_content > a').focus()"
click_link 'Jump to content'
expect(page).to have_css '#main:focus'
end
evaluate_script
中的 JavaScript 似乎没有被正确执行。我在 Chrome 控制台中尝试了相同的 JS ($('#jump_to_content > a').focus()
),但对结果有些不确定,因为在控制台中,链接并未出现,但当点击浏览器视图时,它会出现一小段时间,然后又消失了(因为它不再具有焦点)。在我看来,JS 执行后应该直接显示。
这让我有些不安。非常感谢任何帮助。
更新
我现在已经得出结论,Chrome 的行为是正常的:焦点保持在控制台中,因此元素实际上并没有真正获得焦点,也不会显示。
我还得出结论,Capybara 似乎无法正确处理聚焦元素(和应用 :focus
样式)。
我创建了以下 CSS 规则:
a#jump_to_navigation color: black
&:focus
color: red
为了测试这个,我已经设置了一个非常具体的测试:
visit root_path
selector = 'a#jump_to_navigation'
# Initial style
expect(page.evaluate_script('document.activeElement.id')).to eq '' # Make sure the link isn't focused yet
expect(page.evaluate_script("$('#{selector}').css('color')")).to eq 'rgb(0, 0, 0)' # Color initially is black
# Set focus
page.evaluate_script("$('#{selector}').focus()")
# Focused style
expect(page.evaluate_script('document.activeElement.id')).to eq 'jump_to_navigation' # Make sure the link is focused now
expect(page.evaluate_script("$('#{selector}').css('color')")).to eq 'rgb(255, 0, 0)' # Color is now red
测试会像这样中断:
1) Navigation jump links visually displays them only on focus
Failure/Error: expect(page.evaluate_script("$('#{selector}').css('color')")).to eq 'rgb(255, 0, 0)' # Color is now red
expected: "rgb(255, 0, 0)"
got: "rgb(0, 0, 0)"
(compared using ==)
所以焦点已经正确设置,但是
:focus
样式没有应用。我猜这是PhantomJS的问题吗?我很高兴能够找到解决此问题的方法。