Enzyme: Error Testing Fragments Introduced in v3.4.0

Created on 15 Aug 2018  路  2Comments  路  Source: enzymejs/enzyme

Describe the bug
Not sure if this is a bug or intended behavior/us doing something wrong. It seems that after upgrading to enzyme v3.4+ our tests for components with fragments have started failing.

To Reproduce
Consider the following example:

import React from 'react';
import { expect } from 'chai';
import { shallow } from 'enzyme';

class MyComponent extends React.Component {
  state = { isOpen: false };

  openMe = () => { this.setState({ isOpen: true }); }

  render() {
    return [
      <button onClick={this.openMe}>Click Me</button>,
      <div>Some div</Menu>
    ];
  }
}

// test....
describe('<MyComponent />', function() {
  it('initializes the state', function() {
    const wrapper = shallow(<MyComponent />);
    expect(wrapper.state('isOpen')).to.be.false;
  });
});

Expected behavior
This test worked prior to v3.4. wrapper.state() in that instance returned false as expected. It now causes an error. Namely: "Error: Method "state" is only meant to be run on a single node. 2 found instead."

Additional context

Most helpful comment

@ljharb Thanks for the feedback. I switched to <React.Fragment> and my tests went back to passing as expected. I didn't realize that there were different flavors of 'fragment' - I thought the one was just syntactic sugar for the other. Apparently not the case.

All 2 comments

The support that was added in enzyme v3.4 is for React.Fragment - what's also confusingly referred to as "fragments" is the ability for components to render non-nodes - ie, to render arrays, strings, and numbers. This is not yet supported by enzyme - see #1213.

We're working on adding support for that, but in the meantime, you'll either need to not use this React feature, not test components that use it, or find a way to make the tests pass anyways.

@ljharb Thanks for the feedback. I switched to <React.Fragment> and my tests went back to passing as expected. I didn't realize that there were different flavors of 'fragment' - I thought the one was just syntactic sugar for the other. Apparently not the case.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

heikkimu picture heikkimu  路  3Comments

ivanbtrujillo picture ivanbtrujillo  路  3Comments

thurt picture thurt  路  3Comments

rexonms picture rexonms  路  3Comments

potapovDim picture potapovDim  路  3Comments