Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test which input has the focus when tab button is pressed

I'm building a React autocomplete component and testing it using Jest and React-testing-library.

I have two inputs. When input1(with autocomplete functionality) is in focus, clicking the Tab button should either auto fill input1 with a text if input1 isn't empty, or move the focus to input2(which is the default behaviour of forms) if input1 is empty.

form.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)
        }
    };

form.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.
    });

Currently, in my tests, document.activeElement keeps returning the Body element but I expect it to return either of the two inputs. Also expect(input2).toHaveFocus() fails.

How can I test that the focus has moved from input1 to input2?

like image 740
Mudiaga Ejenavi Avatar asked Oct 23 '20 00:10

Mudiaga Ejenavi


People also ask

What is a testing library?

The Testing Library family of libraries is a very light-weight solution for testing without all the implementation details. The main utilities it provides involve querying for nodes similarly to how users would find them. In this way, testing-library helps ensure your tests give you confidence in your UI code.


1 Answers

I ended up using the @testing-library/user-event library. I replaced fireEvent with userEvent for the Tab press.

My code now looks like this:

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

Reference: https://github.com/testing-library/user-event#tabshift-focustrap

like image 50
Mudiaga Ejenavi Avatar answered Nov 14 '22 17:11

Mudiaga Ejenavi