Skip to content

Instantly share code, notes, and snippets.

@rishabh-ink
Last active June 3, 2018 23:33
Show Gist options
  • Save rishabh-ink/51a9bf40e3f2fa32e9b545e345b1441c to your computer and use it in GitHub Desktop.
Save rishabh-ink/51a9bf40e3f2fa32e9b545e345b1441c to your computer and use it in GitHub Desktop.
Mocking fetch in Jest
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