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. It is also the case if we run it using jsDom 16.
Jest team advised me to open an issue here.
import * as React from 'react';
it('should find active element', () => {
const wrapper = mount(<input />);
const inputNode = wrapper.find('input').getDOMNode();
expect(document.activeElement).not.toBe(inputNode);
inputNode.focus();
expect(document.activeElement).toBe(inputNode); // fails here with expected being null
});
Focused element should be reflected in document.activeElement
This does not follow the issue template; it uses invalid JavaScript syntax, and references undefined functions.
Please edit the post to follow the issue template, producing a sample we can run in Node.js as a single file, and then add a comment. I would also strongly suggest a link to a jsbin or similar. At that time we can reopen and consider this issue.
Interestingly, without enzyme-related stuff it works just fine:
https://runkit.com/wojtekmaj/jsdom-15-2-16-document-activeelement-issue-ok
However, I think it might be tightly coupled with #2586 which is still a regression since v15.2:
https://runkit.com/wojtekmaj/jsdom-15-2-16-document-activeelement-issue
Related: enzymejs/enzyme#2337
Looks like the break is caused by jsdom's increasing strictness about not setting activeElement
to an element outside the document
. The fix is on the client side, using the attachTo
argument to the mount call.