Mud*_*avi 17 javascript reactjs jestjs react-testing-library
我正在构建一个 React 自动完成组件并使用 Jest 和 React-testing-library 对其进行测试。
我有两个输入。当 input1(具有自动完成功能)处于焦点时,单击按钮Tab应该在 input1 不为空时使用文本自动填充 input1,或者在 input1 为空时将焦点移动到 input2(这是表单的默认行为)。
表单.jsx
const onKeyDown = (e) => {
if(e.key === 'Tab' && e.target.value !== '') {
setInput1Text('some-autocomplete-text');
e.preventDefault(); //prevent focus from moving to the next input(input2)
}
};
Run Code Online (Sandbox Code Playgroud)
表单.test.jsx
test('pressing Tab button should move focus to input2 as input1 is empty', () => {
const input1 = container.getElementsByTagName('input')[0];
const input2 = container.getElementsByTagName('input')[1];
fireEvent.change(input1, { target: { value: '' } });
fireEvent.keyDown(input1, { key: 'Tab' });
expect(input2).toBe(document.activeElement) //failing, activeElement returns <Body>
// OR
expect(input2).toHaveFocus(); //failing as well.
});
Run Code Online (Sandbox Code Playgroud)
目前,在我的测试中,document.activeElement不断返回Body元素,但我希望它返回两个输入中的任何一个。也expect(input2).toHaveFocus()失败了。
如何测试焦点是否已从 input1 移至 input2?
Mud*_*avi 27
我最终使用了 @testing-library/user-event 库。我替换fireEvent为userEvent新闻界Tab。
我的代码现在看起来像这样:
import userEvent from '@testing-library/user-event';
test('pressing Tab button should move focus to input2 as input1 is empty', () => {
const input1 = container.getElementsByTagName('input')[0];
const input2 = container.getElementsByTagName('input')[1];
input1.focus();
fireEvent.change(input1, { target: { value: '' } });
userEvent.tab(); //this line made it work
expect(input2).toHaveFocus(); //passing now
});
Run Code Online (Sandbox Code Playgroud)
参考: https: //github.com/testing-library/user-event#tabshift-focustrap
| 归档时间: |
|
| 查看次数: |
31594 次 |
| 最近记录: |