enzyme icon indicating copy to clipboard operation
enzyme copied to clipboard

Invariant Violation error thrown when testing on Stateful Component

Open qingweibinary opened this issue 10 years ago • 2 comments

I am using React 15.

I have a component which call setTimeout in componentWillMount, the function is similar to

class Test extends Component {
    componentWillMount() {
        this.timer = setTimeout(() => this.setState(....), 4000);
    }
    // .....
}

When the timer is triggered, an error is thrown as follow

Invariant Violation: React DOM tree root should always have a node reference.

Here's a related issue on React https://github.com/facebook/react/issues/6232

Is there anyway I could prevent throwing error when testing, without using JSDOM?

Edit1: this.setState(...) to () => this.setState(...)

qingweibinary avatar Mar 28 '16 07:03 qingweibinary

Do you have a componentWillUnmount that clears the timer?

You will have to run wrapper.unmount() after your tests to make sure that the componentWillUnmount gets called.

imontiel avatar Dec 05 '16 23:12 imontiel

You generally don't want to call setState inside componentWillMount.

ljharb avatar Jul 06 '18 05:07 ljharb