enzymejs / chai-enzyme

Chai.js assertions and convenience functions for testing React Components with enzyme
MIT License
787 stars 72 forks source link

Allow `prop` to pass when value is undefined #230

Open HookyQR opened 3 years ago

HookyQR commented 3 years ago

Reason (see last two tests)

  const Inner = () => <div />;
  const Outer = () => <Inner first='string' second={false} third={undefined} />;

  it('has all the things', () => {
    const outer = shallow(<Outer />);
    const inner = outer.find(Inner);

    expect(inner).to.have.props(['first', 'second', 'third']); // pass
    expect(inner)
      .to.have.props(['first', 'second', 'third']) //
      .which.deep.eq(['string', false, undefined]); // pass

    expect(inner).to.have.prop('first'); // pass
    expect(inner).to.have.prop('second'); // pass
    expect(inner).not.to.have.prop('fourth'); // pass
    expect(inner).not.to.have.prop('third'); // pass (incorrectly)
    expect(inner).to.have.prop('third'); // fail
  });

The result of props and prop are inconsistent for properties who's values are undefined.

I would like to have (give the above example)

expect(inner).to.have.prop('fourth', undefined)

to also fail but this may break existing use cases (many tests fail). 😞

ljharb commented 3 years ago

React does not differentiate between a prop that’s present and undefined, vs a prop that’s absent. In other words, if the prop is present and undefined, then the props object does not in fact “have” the prop, per react semantics.

HookyQR commented 3 years ago
      .to.have.props(['first', 'second', 'third']) //

passes.

Chai Enzyme should be able to be used to determine if the property (key) is passes, no matter what the value, without having to check ALL props passed.

ljharb commented 3 years ago

is .to.have.props([]) meant to have "any" or "all" semantics?

HookyQR commented 3 years ago

I didn't change props. It currently has all semantics and matches on key presence, thus matching when the value is undefined. By all, I mean all expected values, but any actual values, ie. actual.length does not have to equal expected.length.

https://github.com/producthunt/chai-enzyme/blob/master/src/assertions/props.js#L6

It will also pass the values through the chain, allowing (and requiring) the (as you say) absent value to be checked. An ACTUAL absent prop would not pass the initial test in props, nor would it in my version of prop.

HookyQR commented 3 years ago

Specifically, the PR will allow

expect().to.have.prop('third')

to have equivalent results to

expect().to.have.props(['third'])

No matter what the value of props.third actually is.