Enzyme: Can't use array destructuring on .find() results

Created on 13 Mar 2018  路  4Comments  路  Source: enzymejs/enzyme

Current behavior

It is not possible to destructure a .find() and run assertions on the individual items, like this:

const [firstTab, secondTab] = wrapper.find('.tab');
expect(firstTab.text()).toBe('Foo'); //  Error: firstTab.text is not a function

Expected behavior

It would be cool if it was possible.

Your environment

API

  • [ ] shallow
  • [x] mount
  • [ ] render

Version

| library | version
| ---------------- | -------
| Enzyme | 3.2.0
| React | 16.1.0

Adapter

  • [x] enzyme-adapter-react-16
  • [ ] enzyme-adapter-react-15
  • [ ] enzyme-adapter-react-15.4
  • [ ] enzyme-adapter-react-14
  • [ ] enzyme-adapter-react-13
  • [ ] enzyme-adapter-react-helper
  • [ ] others ( )
mount shallow feature request help wanted

Most helpful comment

@callumlocke when looking into this, I realized that we already have a .map method - so you can already do wrapper.map(x => x) and you'll get the array you want.

Does this address your use case?

All 4 comments

.find should return the same kind of wrapper as the root; wrappers have iterators: shallow, mount

The issue is that we've defined this to return the element, and not an enzyme wrapper.

I suppose we could add a wrapper instance method like .wrappers() that returned an iterator for .at(i), but I'm not sure it's worth the complexity.

I think a .wrappers() method would be really useful, not just for the destructuring case I outlined above, but for any case where you want to get an array of wrapped elements for running assertions against.

const listItems = [...wrapper.find('li').wrappers()];

Having things as an array lets you use standard methods like .every() and .some() which can be really useful in tests.

You can also use .map() to get a new array of values deduced from each wrapper, which can then be used with any assertion library method that works with arrays. (Jest has several expect matchers that handle arrays intuitively.) Or simply use .forEach() to make an assertion for each item.

@callumlocke when looking into this, I realized that we already have a .map method - so you can already do wrapper.map(x => x) and you'll get the array you want.

Does this address your use case?

I guess so, that's good enough for me. Thanks.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

blainekasten picture blainekasten  路  3Comments

AdamYahid picture AdamYahid  路  3Comments

blainekasten picture blainekasten  路  3Comments

nelsonchen90 picture nelsonchen90  路  3Comments

ahuth picture ahuth  路  3Comments