1

I need to test if the state was set after promise resolved in componentDidMount

class Todos extends React.Component {
    constructor(props) {
        super(props);
        this.state = {};
    }
    componentDidMount() {
        const result = todoStore.fetch();
        mobx.when(
          () => result.state !== mobxUtils.PENDING,
          () => (this.setState({todos: result.value}))
        )

    }
    render() {
        const { todos } = this.state;
        return <div>
            {todos && <ul>
                {todos.map(t => <li>{t.title}</li>)}
            </ul>}
        </div>
    }
}

So far I have..

const wrapper = shallow(<Todos />);

// TODO Need wait until promise is resolved. But how?
// Maybe listen the setState method ?
// PLEASE don't use setTimout.

assert(wrapper.state('todos'))

See the full example..

https://runkit.com/ridermansb/testing-fetch-result-in-componentdidmount/1.0.0

ridermansb
  • 10,779
  • 24
  • 115
  • 226
  • 1
    The main problem is that Todos component knows implementation details such as promises and their resolve mechanism: that's why you find it difficult to test. What you need to do is abstract the fetch method, and provide it as a simple prop. Then you can easily spy the fetch function for testing. – Dmitri Pavlutin Jun 07 '17 at 05:23

0 Answers0