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?