Skip to content

Instantly share code, notes, and snippets.

@rishabh-ink
Last active February 8, 2023 02:20
Show Gist options
  • Save rishabh-ink/b4e45a8b2ac91b24f4201d0927dfdbe2 to your computer and use it in GitHub Desktop.
Save rishabh-ink/b4e45a8b2ac91b24f4201d0927dfdbe2 to your computer and use it in GitHub Desktop.
Mocking and testing fetch with Jest
import { shallow } from 'enzyme';
import ExampleComponent from './ExampleComponent';
describe('ExampleComponent', () => {
it('fetches data from server when server returns a successful response', done => { // 1
const mockSuccessResponse = {};
const mockJsonPromise = Promise.resolve(mockSuccessResponse); // 2
const mockFetchPromise = Promise.resolve({ // 3
json: () => mockJsonPromise,
});
jest.spyOn(global, 'fetch').mockImplementation(() => mockFetchPromise); // 4
const wrapper = shallow(<ExampleComponent />); // 5
expect(global.fetch).toHaveBeenCalledTimes(1);
expect(global.fetch).toHaveBeenCalledWith('https://url-of-your-server.com/example/json');
process.nextTick(() => { // 6
expect(wrapper.state()).toEqual({
// ... assert the set state
});
global.fetch.mockClear(); // 7
done(); // 8
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment