Last active
June 3, 2018 23:33
-
-
Save rishabh-ink/51a9bf40e3f2fa32e9b545e345b1441c to your computer and use it in GitHub Desktop.
Mocking fetch in Jest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react'; | |
class ExampleComponent extends Component { | |
componentDidMount() { | |
const fetchedData = this.fetchDataFromServer(); | |
// ... do something with fetchedData e.g. set the data | |
} | |
async fetchDataFromServer() { | |
try { | |
const response = await fetch('https://url-of-your-server.com/example/json'); // 1 | |
return await response.json(); // 2 | |
} catch (error) { | |
// ... gracefully handle error | |
} | |
} | |
// ... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment