Last active
September 13, 2018 09:08
-
-
Save nathf/849c209d0239f4599591287df9b100ee to your computer and use it in GitHub Desktop.
Mock Fetch with Jest
This file contains hidden or 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
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