Posts

Showing posts with the label fetch-api

How to unit test a React component that renders after fetch has finished?

How to unit test a React component that renders after fetch has finished? I'm a Jest/React beginner. In jest's it I need to wait until all promises have executed before actually checking. it My code is similar to this: export class MyComponent extends Component { constructor(props) { super(props); this.state = { /* Some state */ }; } componentDidMount() { fetch(some_url) .then(response => response.json()) .then(json => this.setState(some_state); } render() { // Do some rendering based on the state } } When the component is mounted, render() runs twice: once after the constructor runs, and once after fetch() (in componentDidMount() ) finishes and the chained promises finish executing). render() fetch() componentDidMount() My testing code is similar to this: describe('MyComponent', () => { fetchMock.get('*', some_response); it('renders something', () => {...