Skip to content

Instantly share code, notes, and snippets.

@nathf
Last active September 13, 2018 09:08
Show Gist options
  • Save nathf/849c209d0239f4599591287df9b100ee to your computer and use it in GitHub Desktop.
Save nathf/849c209d0239f4599591287df9b100ee to your computer and use it in GitHub Desktop.
Mock Fetch with Jest
const mockResponse = (status, statusText, response) => {
return new window.Response(response, {
status: status,
statusText: statusText,
headers: {
'Content-type': 'application/json'
}
});
};
test('fetch something', () => {
window.fetch = jest.fn().mockImplementation(() =>
Promise.resolve(mockResponse(200, null, '{"foo":"bar"}')));
fetch('/foo/bar')
.then(r => r.json())
.then(json => expect(json.foo).toEqual('bar'));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment