Last active
May 24, 2017 05:52
-
-
Save jtrein/cb0359991633e31e9bba40a3e18ccdbe to your computer and use it in GitHub Desktop.
Mock Fetch with 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
// __mocks__/mockFetch.js | |
const MockFetch = responseJson => ( | |
() => ( | |
new Promise(resolve => resolve({ | |
json: () => JSON.parse(JSON.stringify(responseJson)), | |
})) | |
) | |
); | |
export default MockFetch; | |
// app.test.js | |
/*--------------USAGE WITH JEST------------------*/ | |
// note: for usage with other frameworks look up async testing | |
import MockFetch from '../__mocks__/mockFetch'; | |
test('SomeAsyncFunc returns json parsed value from Promise', async () => { | |
global.fetch = MockFetch({ | |
cat: 'meow', | |
}); | |
const response = await SomeAsyncFunc(); | |
expect(response.cat).toBe('meow'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This isn't a Jest mock. This just shows how I use it with
jest
and the global polyfill forwhatwg-fetch
. You'll probably want to resetglobal.fetch
to avoid shared state between tests (i.e. calling it with no methods will return the previous data).