Enzyme: .find('.css-selector') returns empty ShallowWrapper.

Created on 7 Jun 2018  路  7Comments  路  Source: enzymejs/enzyme

Solution
See last post.

Describe the bug
.find() returns empty ShallowWrapper when searching by CSS selector.

To Reproduce

[*.test.js]
// ...all required imports

configure({ adapter: new Adapter() });
const wrapper = shallow((
    <div className='.klas'></div>
));

it('has a class', () => {
    // search by tag works, test succeeds
    expect(wrapper.find('div').props().className.indexOf('.klas') >= 0).toEqual(true);

    // search by css selector does not, test fails
    expect(wrapper.find('.klas')).toHaveLength(1);    
});

Expected behavior
Upon the .find() call, get ShallowWrapper containing the node which has the CSS selector passed as the argument.

Workaround
wrapper.find('div[className=".klas"]') or
wrapper.find({ className: '.klas' })

Software

[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]

NodeJS v6.11.4
OS: Ubuntu 17.10

Most helpful comment

That was the dumbest mistake.

const wrapper = shallow((
    <div className='.klas'></div> // Class name should not start with a dot.
));

I have to go back to learning basics :D.
_hthuong09_ was right, I didn't get what he said right away.

All 7 comments

Also just found out:

// returns false
console.log(wrapper.find('div').hasClass('sample'));

// returns true with the warning to avoid using css selector
console.log(wrapper.find('div').hasClass('.sample')); 

wrapper.find('.sample') means looking for node which has sample class, not .sample.
Try wrapper.find('.\\.sample') (haven't tested).

Didn't work! :(

screenshot_20180606_185949

wrapper.find('.sample') means looking for node which has sample class

Yeah, right, that's what I am saying,
Expected behaviour is to get a node containing specified css selector, but find() returns an empty wrapper with the length of zero.

Found workaround:
wrapper.find('div[className=".klas"]') or
wrapper.find({ className: '.klas' }).

That was the dumbest mistake.

const wrapper = shallow((
    <div className='.klas'></div> // Class name should not start with a dot.
));

I have to go back to learning basics :D.
_hthuong09_ was right, I didn't get what he said right away.

Just to add, found similar issue if we accidentally/incorrectly use class instead of className in JSX:

// incorrect
const wrapper = shallow((
<div class="klas"></div> // enzyme is not finding using class selector wrapper.find('.klas'); ));`

// correct
const wrapper = shallow((
<div className="klas"></div> // enzyme is able to find using class selector wrapper.find('.klas'); ));

Was this page helpful?
0 / 5 - 0 ratings