Skip to content

Instantly share code, notes, and snippets.

@markusbergh
Created January 10, 2021 00:31
Show Gist options
  • Save markusbergh/036fc3bef47bbc31b3396cb3fca602d5 to your computer and use it in GitHub Desktop.
Save markusbergh/036fc3bef47bbc31b3396cb3fca602d5 to your computer and use it in GitHub Desktop.
Mocking Fetch API by using Jest
/**
* 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