Jest/Enzyme Error: “Method 'setState' is only meant to run on a single node. 3 found instead.”

前端 未结 1 1298
温柔的废话
温柔的废话 2020-12-21 23:58

I\'m fairly new to testing with Enzyme/Jest on a React application, so perhaps there\'s something wrong with the way I\'m setting up my test.

I specifically want to

相关标签:
1条回答
  • 2020-12-22 00:23

    wrapper.update() shouldn't be there. It doesn't return a promise and cannot be awaited. Enzyme already runs lifecycle hooks by default, including componentDidMount.

    The problem is componentDidMount isn't testable and doesn't expose a promise. It should be extracted to a method that returns a promise that could be chained:

    loadSomething() {
        const candidateId = this.props.match.params.candidate_id;
    
        return Promise.all([
          this.props.expressApi.applicationsOfCandidate(candidateId),
          this.props.expressApi.candidateReviewStatus(candidateId),
        ]).then((data) => {
          const candidateInfo = data[0][this.props.match.params.candidate_id];
          const reviewInfo = data[1][0];
          this.setState({ ... });
        }).catch((err) => {
          this.props.handleError(err);
          this.setState({
            error: err,
          });
        });
    }
    
    componentDidMount() {
        this.loadSomething();
    }
    

    Then it can be stubbed in one test:

    jest.stub(Candidate.prototype, 'loadSomething')
    shallow(<Candidate .../>);
    expect(shallow.instance().loadSomething).toHaveBeenCalledTimes(1);
    

    And tested directly in another:

    shallow(<Candidate .../>, { disableLifecycleMethods: true });
    await shallow.instance().loadSomething();
    expect(shallow.state(...))...
    
    0 讨论(0)
提交回复
热议问题