How to fix document.getElementById() returns null on component with Jest and Enzyme?

Sometimes, we want to fix document.getElementById() returns null on component with Jest and Enzyme.

In this article, we’ll look at how to fix document.getElementById() returns null on component with Jest and Enzyme.

How to fix document.getElementById() returns null on component with Jest and Enzyme?

To fix document.getElementById() returns null on component with Jest and Enzyme, we can attach the mounted component into the DOM.

For instance, we write:

import {
  mount
} from 'enzyme';

beforeAll(() => {
  const div = document.createElement('div');
  window.domNode = div;
  document.body.appendChild(div);
})

test("Test component with mount + document query selector", () => {
  const wrapper = mount(<YourComponent/>, {
    attachTo: window.domNode
  });
});

to create a div with createElement before any test is run.

And then we call appendChild to append the div to the body element.

Then in a test, we call mount to mount the component we’re testing.

And we set attachTo to the div we created in the beforeAll hook.

Conclusion

To fix document.getElementById() returns null on component with Jest and Enzyme, we can attach the mounted component into the DOM.