Skip to content

this is undefined in bound functions when shallow rendering #1756

@adityavm

Description

@adityavm

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions