我正在创建一个基于用户键盘事件(如按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"
仍然具有焦点。
答案 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()
})