Last active
February 8, 2023 02:20
-
-
Save rishabh-ink/b4e45a8b2ac91b24f4201d0927dfdbe2 to your computer and use it in GitHub Desktop.
Mocking and testing 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
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