Tab键按下不会更改焦点元素

时间:2019-04-30 11:29:43

标签: javascript reactjs jestjs jsdom react-testing-library

我正在创建一个基于用户键盘事件(如按Enter,箭头等)处理焦点的组件。

最好测试一下组件是否忽略按键按下时的Tab键。

但是,在触发keydown选项卡事件时,焦点不会像在浏览器中那样发生变化。


给出Component.js中的react组件

import React from 'react'

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

和以下测试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()
  })
})

测试失败,因为元素data-testid="one"仍然具有焦点。

See CodeSandbox for an editable version of this code

1 个答案:

答案 0 :(得分:1)

当今可行的解决方案是使用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()
})