【发布时间】: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" 仍然有焦点。
【问题讨论】:
-
@Pants 我想可能是这样。几个问题......他们是同一个图书馆吗?此问题不涉及模拟文档上的按键。
标签: javascript reactjs jestjs jsdom react-testing-library