enzyme: hasClass does not work on root ReactWrapper

I think this is because MountedTraversal#instHasClassName short circuits to false if the instance does not pass the isDOMComponent check. Could we relax the check?

Example test case (React 0.14):

const shallowComponent = shallow(<Video src="example.mp4" />);
const mountComponent = mount(<Video src="example.mp4" />);

// From ShallowTraversal
// Works!
assert.equal(shallowComponent.node.props.className, 'Video');

// Works!
assert.isTrue(shallowComponent.hasClass('Video'));

// Fails :( because isDOMComponent(mountComponent.node) is false
// Would otherwise pass
assert.isTrue(mountComponent.hasClass('Video'));

// From MountedTraversal (without isDOMComponent check)
// Works!
assert.equal(findDOMNode(mountComponent.node).className, 'Video');

// Works! ... but seems unnecessary
assert.isTrue(mountComponent.find('.Video').hasClass('Video'));

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 2
  • Comments: 17 (5 by maintainers)

Most upvoted comments

I’m seeing this same behavior in 2.3.0

I just spent hours trying to figure out why tests were failing using hasClass. wrapper.html() shows me the class is there, and yet hasClass still returns false. This is really frustrating and unexpected behaviour, which wastes everybody’s time.

May I suggest we document this in the readme, with some alternatives for checking if the wrapper has a class?

Have the same problem on 3.0.0 with react 0.16, .html() shows the class is in there but hasClass returns false.

I’m still seeing this in 2.4.1 as well. I’m not sure if it’s for the same reason, but it has the same behavior of hasClass working with shallow, but not mount.

Has this commit made it into an updated npm package? I’m still seeing it in 2.7.1.