简体   繁体   English

Tab 按键不会改变焦点元素

[英]Tab keypress doesn't change focused element

I'm creating a component which handles focus based on user keyboard events (like pressing enter, arrows, etc).我正在创建一个基于用户键盘事件(如按 Enter、箭头等)处理焦点的组件。

It'd be preferable to test that the component ignores the tab key on keydown.最好测试该组件是否忽略了 keydown 上的 tab 键。

However, on firing the keydown tab event, the focus doesn't change like it would in a browser.但是,在触发 keydown tab 事件时,焦点不会像在浏览器中那样改变。


Given the react component in Component.js鉴于Component.js的 react Component.js

import React from 'react'

export default () => (
  <>
    <button data-testid="one">
      one
    </button>
    <button data-testid="two">
      two
    </button>
  </>
)

and the following test Component.test.js和以下测试Component.test.js

import React from 'react'
import 'jest-dom/extend-expect'
import { cleanup, fireEvent, render, wait } from 'react-testing-library'
import Component from './Component'

afterEach(cleanup)

it('changes focus on tab', async () => {
  const { getByTestId } = render(<Component />)
  const one = getByTestId('one')
  const two = getByTestId('two')

  one.focus()

  expect(one).toHaveFocus()

  fireEvent.keyDown(one, {
    key: 'Tab',
    code: 9,
    charCode: 9
  })

  await wait(() => {
    expect(two).toHaveFocus()
  })
})

the test fails, as the element data-testid="one" still has focus.测试失败,因为元素data-testid="one"仍然具有焦点。

See CodeSandbox for an editable version of this code 有关此代码的可编辑版本,请参阅 CodeSandbox

A working solution nowadays would be to use userEvent.tab() instead of fireEvent.keyDown() .现在一个userEvent.tab()解决方案是使用userEvent.tab()而不是fireEvent.keyDown()

 import '@testing-library/jest-dom' import userEvent from '@testing-library/user-event' import { render, screen } from '@testing-library/react' import Component from './buttons' it('changes focus on tab', async () => { render(<Component />) const one = screen.getByTestId('one') const two = screen.getByTestId('two') one.focus() expect(one).toHaveFocus() userEvent.tab() expect(two).toHaveFocus() })

You can simply do this with react-testing-library itself.您可以简单地使用 react-testing-library 本身来做到这一点。 All you have to do is this:你所要做的就是:

Use the fireEvent.blur(<your-input-element-here>)使用fireEvent.blur(<your-input-element-here>)

import { fireEvent } from '@testing-library/react';

it('changes focus on tab', async () => {
  render(<Component />)
  const one = screen.getByTestId('one')
  const two = screen.getByTestId('two')

  // fires the onBlur event
  fireEvent.blur(one)

  expect(one).not.toHaveFocus()
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM