I have a component that triggers a fetch
request when it mounts and then displays the results.
I've been struggling to create a test snapshot of this component after the request is completed. I've searched on various forums like SO but haven't found a solution yet. Here are some related questions on SO that were not helpful:
- Async component snapshot using Jest and Redux
- How do test async components with Jest?
- React+Jest - Testing async components and waiting for mount
- How to take a jest snapshot after axios fetched data in componentDidMount?
Here's the mock of my fetch
:
// Mocking the global.fetch included in React Native
global.fetch = jest.fn()
// Helper to mock a success response (only once)
fetch.mockResponseSuccess = (body, status = 200) => {
fetch.mockImplementationOnce(() =>
Promise.resolve({
status,
json: () => Promise.resolve(JSON.parse(body))
})
)
}
// Helper to mock a failure response (only once)
fetch.mockResponseFailure = error => {
fetch.mockImplementationOnce(() => Promise.reject(error))
}
The simplified version of the component:
export class Posts extends Component {
constructor(props) {
super(props)
this.state = {
items: [],
loading: false
}
this._getItems()
}
async _getItems() {
const resp = await fetch(
"/user/recent_posts",
{
method: "GET"
}
)
this.setState({
items: resp.json["data"],
})
}
render() {
// renders this.state.items
}
Here's the test I'm running:
test("view renders correctly", async done => {
fetch.mockResponseSuccess(
JSON.stringify({
data: [
{ caption: "test", likes: 100 },
{ caption: "test2", likes: 200 }
]
})
)
const wrapper = await shallow(<Posts />)
expect(wrapper).toMatchSnapshot()
done()
})
The problem is that even after the fetch request completes, this.state.items
in the snapshot remains empty.