Enzyme: After mount, I'm unable to getElementById from jsdom

Created on 27 Mar 2017  路  2Comments  路  Source: enzymejs/enzyme

This is very similar to #524 but can't find the reason why my jsdom setup is different than the reported solved one in there.

I'm trying to test a component I'm working on dstpierre/react-trix. In my componentDidMount I'm calling document.getElementById and it's returning null when using this test case:

it("renders the Trix editor", function () {
    const handleChange = spy();
    const wrapper = mount(<TrixEditor onChange={handleChange} value="testing 1234" />);
    console.log(global.document._ids);
    console.log(wrapper.debug());
    expect(handleChange).to.have.property('callCount', 1);
  });

This is a quick pseudo code of the component:

componentDidMount() {
  this.editor = document.getElementById("editor-id"); // <- this returns null when testing with enzyme/jsdom
}
render() {
  return (
    <div>
      {React.createElement("trix-editor", { id: "editor-id"})}
  </div>
 )
}

I have this setup script for mocha:

import { jsdom } from "jsdom";

global.document = jsdom(`<!doctype html><html><head></head><body><script src="https://rawgit.com/basecamp/trix/master/dist/trix.js"></script></body></html>`);
global.window = document.defaultView;

global.navigator = {
  userAgent: 'node.js'
};

Object.keys(document.defaultView).forEach((property) => {
  if (typeof global[property] == "undefined") {
    global[property] = document.defaultView[property];
  }
});

The output of the wrapper.debug() is this:

<TrixEditor onChange={[Function]} value="testing 1234">
  <div>
    <trix-editor id="editor-id" input="input-id" />
    <input type="hidden" id="input-id" value="testing 1234" />
  </div>
</TrixEditor>

But the getElementById in the componentDidMount returns null. And if I print document.body.innerHtml in the componentDidMount I only see the content that I have in the setup script and not the mounted React component.

I'm probably missing something basic here, I've checked your documentation and the sample you provide for the mount is pretty much what I have. Can anyone give some help here, that would be highly appreciated.

Most helpful comment

You should be using ref callbacks, never normal DOM traversal, to get access to nodes in componentDidMount.

All 2 comments

You should be using ref callbacks, never normal DOM traversal, to get access to nodes in componentDidMount.

@ljharb thank you for the heads-up, I was reverting to DOM traversal due to <trix-editor /> being a non-react / non html component that I was loading directly via React.createElement. But I grabbed the parent div via ref callbacks and was able to get the first child.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ahuth picture ahuth  路  3Comments

aweary picture aweary  路  3Comments

abe903 picture abe903  路  3Comments

modemuser picture modemuser  路  3Comments

blainekasten picture blainekasten  路  3Comments