We use jest tests with expect(document.activeElement).toBe(myElement) pattern to determine if an element got correctly focused after an interaction. After upgrading to jest 25 (jsdom 15) all such tests broke, document.activeElement appears to be always null.
For example the following test works with Jest 24.x but not with 25.x
// example.spec.jsimport * as React from 'react';
it('should find active element', () => {
const wrapper = mount(<input />);
const inputNode = wrapper.find('input').getDOMNode();
inputNode.focus();
expect(document.activeElement).toBe(inputNode); // fails with 'expected' being null
});
What is the best way to test if an element is focused using Jest 25.x?
The document.activeElement property is not available in Jest tests because Jest runs tests in a node environment, not in a browser. You can use the .focused property of the input element's DOM node to determine if it is currently focused.
For example:
it('should find active element', () => { const wrapper = mount(<input />); const inputNode = wrapper.find('input').getDOMNode(); inputNode.focus(); expect(inputNode.focused).toBe(true); });
Alternatively, you can use the focus method of the ReactTestUtils module to focus the element in your test and then use the isFocused method of the ReactTestUtils module to check if the element is focused.
For example:
import * as ReactTestUtils from 'react-dom/test-utils'; it('should find active element', () => { const wrapper = mount(<input />); const inputNode = wrapper.find('input').getDOMNode(); ReactTestUtils.focus(inputNode); expect(ReactTestUtils.isFocused(inputNode)).toBe(true); });