Skip to content

Instantly share code, notes, and snippets.

@jtrein
Last active May 24, 2017 05:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jtrein/cb0359991633e31e9bba40a3e18ccdbe to your computer and use it in GitHub Desktop.
Save jtrein/cb0359991633e31e9bba40a3e18ccdbe to your computer and use it in GitHub Desktop.
Mock Fetch with Jest
// __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');
});
@jtrein
Copy link
Author

jtrein commented May 24, 2017

This isn't a Jest mock. This just shows how I use it with jest and the global polyfill for whatwg-fetch. You'll probably want to reset global.fetch to avoid shared state between tests (i.e. calling it with no methods will return the previous data).

@jtrein
Copy link
Author

jtrein commented May 24, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment