Created
January 10, 2021 00:31
-
-
Save markusbergh/036fc3bef47bbc31b3396cb3fca602d5 to your computer and use it in GitHub Desktop.
Mocking Fetch API by using 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
/** | |
* Minimal mocking | |
*/ | |
// `global` is available in both node and browser environment | |
/* | |
global.fetch = () => | |
Promise.resolve({ | |
json: () => Promise.resolve({ | |
foo: 'bar', | |
}) | |
}) | |
*/ | |
/** | |
* Jest mocking | |
*/ | |
describe('Testing', () => { | |
beforeAll(() => { | |
jest.spyOn(global, 'fetch') | |
}) | |
beforeEach(() => { | |
/* | |
global.fetch.mockImplementation(() => | |
Promise.resolve({ | |
json: () => Promise.resolve({ | |
foo: 'bar' | |
}) | |
}) | |
) | |
*/ | |
global.fetch.mockResolvedValueOnce({ | |
json: () => { | |
foo: 'bar' | |
} | |
}) | |
} | |
}) | |
// expect(global.fetch).toHaveBeenCalledTimes(1) | |
// expect(global.fetch).toHaveBeenCalledWith('url://') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment