How to Test Asynchronous Request in React
Last updated
Was this helpful?
Last updated
Was this helpful?
In this post, we'll learn these
How to test asynchronous request in the React componentDidMount lifecycle.
How to test async code in Jest to avoid the false positive problem if Jest doesn't know it should wait for the test to end.
How to test if request data have been set in our component state
Source code is .
Steps:
import axios from the node_modules
use jest.spyOn
to override theget
method with our own mock function, req
The req
function returns a Promise which will return some data after 1 second
Since we perform an async request in componentDidMount
, we'll make it an async
function in order to test it.
Next, we test if axios.get
have been called after componentDidmount
resolved.
Lastly, to verify if the received data has been passed in our compoent state, we use Jest .toHaveProperty
method, to check if property and values are expected.