chai-enzyme icon indicating copy to clipboard operation
chai-enzyme copied to clipboard

descendants(selector) returns true for root element

Open lukebatchelor opened this issue 8 years ago • 3 comments

I'm just wondering if the following is truly the expected behaviour (from the readme)

import React from 'react'
import {mount, render, shallow} from 'enzyme'

class User extends React.Component {
  render () {
    return (
      <span>User</span>
    )
  }
}

class Fixture extends React.Component {
  render () {
    return (
      <div id='root'>
        <User />
      </div>
    )
  }
}

const wrapper = mount(<Fixture />) // mount/render/shallow when applicable

expect(wrapper).to.have.descendants('#root')
expect(wrapper).to.have.descendants(User)

should the expect(wrapper).to.have.descendants('#root') line really be passing? I would expect that descendants would only check actual descendants, not the root level element?

That could just be my interpretation of the word though, so happy to close this, just wanted to check.

lukebatchelor avatar Jan 10 '17 03:01 lukebatchelor

Descendants uses enzyme find internally which always starts at the top of the render, NOT the descendants of the first element of the render. I'm pretty sure this is intended behaviour and all enzyme methods and as a result chai-enzyme methods will have the same behaviour.

To achieve what you're trying to do you could do something like:

const firstChild = wrapper.children().first();
expect(firstChild).to.not.have.descendants('#root');

marcodejongh avatar Jan 10 '17 05:01 marcodejongh

Wondering if we should alias this to

expect(wrapper).to.have.found('#root')

to avoid the confusion

ayrton avatar Jan 30 '17 02:01 ayrton

Not sure if found communicates it clearly enough. Maybe the descendants behaviour can be merged into contains?

marcodejongh avatar Feb 06 '17 02:02 marcodejongh