为了账号安全,请及时绑定邮箱和手机立即绑定

按下选项卡按钮时如何测试哪个输入具有焦点

按下选项卡按钮时如何测试哪个输入具有焦点

Qyouu 2023-06-09 10:42:17
我正在构建一个 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)        }    };表单.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.    });目前,在我的测试中,document.activeElement不断返回Body元素,但我希望它返回两个输入中的任何一个。也expect(input2).toHaveFocus()失败了。如何测试焦点是否已从 input1 移至 input2?
查看完整描述

2 回答

?
12345678_0001

TA贡献1802条经验 获得超5个赞

我最终使用了@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

    });

查看完整回答
反对 回复 2023-06-09
?
MM们

TA贡献1886条经验 获得超2个赞

如果您执行以下操作,函数 fireEvent.keyDown 应该适合您:

  • 组件和测试都必须使用 KeyDown,(使用 KeyPressed 是我的问题之一)

  • 然后可以像这样调用 fireEvent:

      fireEvent.keyDown(Element, {key: 'Tab', code: 'Tab', charCode: 9})
查看完整回答
反对 回复 2023-06-09
  • 2 回答
  • 0 关注
  • 74 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信