enzymejs / enzyme-matchers

Jasmine/Jest assertions for enzyme
MIT License
892 stars 116 forks source link

`toContainMatchingElement` considers `className` prop rather than actual HTML #371

Closed iangreenleaf closed 2 years ago

iangreenleaf commented 2 years ago

If a component is passed a className but doesn't use it, toContainMatchingElement will still pass when given a class name selector. It seems like it must be detecting the className prop, even though it's never rendered to the HTML. For example:

      const MyElement = (_props) => (<div className='abcd' />);
      const el = mount(<MyElement className='foobar' />);
      console.log(el.html()); // Prints: <div class="abcd"></div>
      expect(el).toContainMatchingElement('.foobar'); // passes
ljharb commented 2 years ago

That's expected - el DOES contain <MyElement className='foobar' />.

Try expect(el.hostNodes()).toContainMatchingElement('.foobar');.

iangreenleaf commented 2 years ago

Upon further investigation, I've realized that this is an enzyme problem, not this library. I had initially misread a test that made me incorrectly think the problem was isolated to this library. Sorry for the mistaken report!

ljharb commented 2 years ago

@iangreenleaf i assume it's an enzyme usage problem, as i've indicated? if not, please file an issue on enzyme.

iangreenleaf commented 2 years ago

@ljharb your hostNodes() suggestion didn't work because it doesn't seem to return the single element (it shows up as an empty set). But I was able to get a correct test by using a similar strategy of calling render() and Cheerio functions to parse the actual HTML.

I suspect I would get told the same thing by enzyme, that this is working as expected. I personally think it's pretty wild that enzyme would match a CSS selector for a class name that is not being rendered, but maybe I'm just a curmudgeon.

ljharb commented 2 years ago

No, I agree with you - the issue is likely that selectors match the components themselves as well as the things they render.

render() should generally be avoided and rarely needed, and i think mount should work for this case. If you file an issue on enzyme we can try to work out the problem.

iangreenleaf commented 2 years ago

Thanks, nice to know I'm not alone in this! Filed https://github.com/enzymejs/enzyme/issues/2560 for it.