I am currently facing an issue with mocking the global fetch function using Jest and dealing with the Response type. Specifically, I only require the response.ok and response.json properties, but I am struggling to set the return data of fetch without specifying all the required properties individually. Is there a way to achieve this without writing out all the properties?
Here is a snippet of my code:
describe('steam data fetch function', () => {
const fetchMock = jest.spyOn(global, 'fetch').mockImplementation(
jest.fn(() =>
Promise.resolve({
ok: false,
json: () => Promise.resolve({ data: 'empty' }),
})
) as jest.Mock
);
// Begin tests
test('handles invalid data correctly', () => {
fetchMock.mockResolvedValueOnce({
ok: false,
json: () => Promise.resolve({ data: 'test1' }),
}) as jest.Mock;
// expect function using fetch to...
});
// more tests
// each test sets new fetchMock.mockResolvedValueOnce
});
While using fetchMock.mockResolvedValueOnce, I encountered a tsError stating that certain properties of the Response type are missing. I tried adding one missing property, but I want to avoid manually specifying all properties.
After some helpful comments, I found a new working version:
test('handles invalid data correctly', () => {
fetchMock.mockResolvedValueOnce({
ok: false,
json: () => Promise.resolve({ data: 'test1' }),
} as unknown as Response);
// expect function using fetch to...
});
While I understand that a more comprehensive approach might be better, this solution works well for my current requirements.