Enzyme: Enzyme 3/React 16: `hasClass()` no longer works on wrapper using `mount()`

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

Current behavior

Cannot assert hasClass on wrapper node using mount.

Sample code

Please clone https://github.com/kcjpop/enzyme-has-class

Expected behavior

Snippet below should work

class Foo extends React.Component {
  render() {
    return <h1 className="foo bar">Hello World</h1>
  }
}

test('Foo', () => {
  const wrapper = mount(<Foo />)
  expect(wrapper.hasClass('foo')).toBe(true)
})

A bit playing showed me the diff below could make tests passed, but I'm not sure if it's a correct way to do.

diff --git a/packages/enzyme/src/RSTTraversal.js b/packages/enzyme/src/RSTTraversal.js
index 19b2a3b..5fccc17 100644
--- a/packages/enzyme/src/RSTTraversal.js
+++ b/packages/enzyme/src/RSTTraversal.js
@@ -14,7 +14,7 @@ export function childrenOfNode(node) {
 }

 export function hasClassName(node, className) {
-  let classes = propsOfNode(node).className || '';
+  let classes = propsOfNode(node.rendered && node.rendered.props ? node.rendered : node).className || '';
   classes = String(classes).replace(/\s/g, ' ');
   return ` ${classes} `.indexOf(` ${className} `) > -1;
 }
mount question v3 bugs

Most helpful comment

This is because a mount wrapper is the component, so it has no classes - try wrapper.childAt(0).hasClass?

All 2 comments

This is because a mount wrapper is the component, so it has no classes - try wrapper.childAt(0).hasClass?

Thanks @ljharb, that works. Before upgrading the test passed so I expected its old behavior. Closing this issue now.

Was this page helpful?
0 / 5 - 0 ratings