enzyme: `this` is undefined in bound functions when shallow rendering

Describe the bug The following test passes in 3.4.1 but fails in 3.4.2.

class Comp extends Component {
  state = {
    key: "",
  }

  componentDidMount() {
    this.instanceFunction();
  }

  instanceFunction = () => this.setState(() => ({ key: "value" }));

  render() {
    const { key } = this.state;
    return null;
  }
}

it("should work", () => {
  shallow(<Comp />);
});

The error in 3.4.2 is:

FAIL src/test.js
  ✕ should work (16ms)

  ● should work

    Method “setState” is only meant to be run on a single node. undefined found instead.

      11 |   }
      12 |
    > 13 |   instanceFunction = () => this.setState(() => ({ key: "value" }));
         |                                 ^
      14 |
      15 |   render() {
      16 |     const { key } = this.state;

      at ShallowWrapper.single (node_modules/enzyme/build/ShallowWrapper.js:1718:17)
      at ShallowWrapper.setState (node_modules/enzyme/build/ShallowWrapper.js:499:14)
      at Comp.ShallowWrapper.instance.setState (node_modules/enzyme/build/ShallowWrapper.js:184:33)
      at Comp.setState [as instanceFunction] (src/test.js:13:33)
      at Comp.instanceFunction [as componentDidMount] (src/test.js:10:10)
      at node_modules/enzyme/build/ShallowWrapper.js:189:20
      at Object.batchedUpdates (node_modules/enzyme-adapter-react-16/build/ReactSixteenAdapter.js:392:22)
      at new ShallowWrapper (node_modules/enzyme/build/ShallowWrapper.js:188:24)
      at shallow (node_modules/enzyme/build/shallow.js:21:10)
      at Object.<anonymous> (src/test.js:22:3)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        2.147s
Ran all test suites matching /src\/test.js/i.
error Command failed with exit code 1.

To Reproduce Steps to reproduce the behavior:

  1. Run the above test with enzyme@3.4.2

Expected behavior The test should pass.

Desktop (please complete the following information):

  • OS: Mac OSX (but also fails in Windows)
  • Browser n/a
  • Version n/a

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 20
  • Comments: 16 (7 by maintainers)

Commits related to this issue

Most upvoted comments

+1 yes happening to us too, due to https://github.com/airbnb/enzyme/blob/a50570d847fac11dc122c43651107e46ba03de73/packages/enzyme/src/ShallowWrapper.js#L177-L180 as setState is getting appended to instance. I think we should avoid addingsetState to instance as then also the code will get executed without appending instance.

@ljharb Thank you! I’m reviewing it.