score:6

Accepted answer

From the React#setState,

setState(updater, [callback])

setState() enqueues changes to the component state. The setState doesn't immediately update the state. setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall.Instead, use componentDidUpdate or a setState callback (setState(updater, callback))

Solution 1:

Remove callback from setState;

      wrapper.setState({ user });
      wrapper.instance().handleUnauth();
      const userState = wrapper.state('user');
      expect(userState).toEqual(null);

Solution 2:

Read the updated state in the callback parameter of setState callback

wrapper.setState({ user }, (userState) => {

      wrapper.instance().handleUnauth();
      //const userState = wrapper.state('user'); // comment it.
      expect(userState).toEqual(null);
});

Related Query

More Query from same tag