【问题标题】:Tab keypress doesn't change focused elementTab 按键不会改变焦点元素
【发布时间】:2019-04-30 11:29:43
【问题描述】:

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

最好测试组件是否忽略 keydown 上的 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

【问题讨论】:

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


【解决方案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()
})

【讨论】:

    【解决方案2】:

    您可以简单地使用 react-testing-library 本身来执行此操作。您所要做的就是:

    使用fireEvent.blur(&lt;your-input-element-here&gt;)

    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()
    })
    

    【讨论】:

      猜你喜欢
      • 2023-01-13
      • 2016-07-03
      • 2018-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多