如何测试Get请求处理函数的.json()异常捕获分支?
Great question! To trigger the catch block in your get function, there are two key scenarios you can mock—let's break them down, with a focus on forcing the json() method to fail (since that's what you're asking about):
1. Mock json() to Reject (Simulate Invalid JSON)
The json() method of a Fetch Response returns a Promise that rejects if the response body isn't valid JSON. To replicate this realistically in your test, you need to mock the fetch function to return a Response-like object where the json() method returns a rejected Promise.
Here's a concrete Jest implementation:
test('get function catches JSON parsing errors', async () => { // Mock fetch to resolve with a fake Response whose json() rejects global.fetch = jest.fn(() => Promise.resolve({ json: jest.fn(() => Promise.reject(new Error('Invalid JSON payload'))) }) ); const result = await get('https://test-url.com'); // Verify the catch block returned the error as a string expect(result).toBe('Error: Invalid JSON payload'); // Ensure fetch was called with the correct URL expect(fetch).toHaveBeenCalledWith('https://test-url.com'); });
Why your previous attempts didn't work
Mocking the response as a raw string/array doesn't mimic real Fetch API behavior: actual fetch returns a Response object, not a primitive value. When you tried that, calling rawResponse.json() would throw a TypeError (since strings/arrays don't have a json() method)—which would trigger the catch block, but it's not a realistic simulation of invalid JSON parsing. The approach above matches real-world failure scenarios.
2. Mock fetch to Reject (Simulate Network Errors)
If you also want to test the scenario where the fetch request itself fails (e.g., no internet connection), you can mock fetch to return a rejected Promise directly:
test('get function catches network errors', async () => { global.fetch = jest.fn(() => Promise.reject(new Error('Network connection failed'))); const result = await get('https://test-url.com'); expect(result).toBe('Error: Network connection failed'); });
Cleanup Tip
Don't forget to reset your mocks after each test to avoid cross-test contamination:
afterEach(() => { jest.restoreAllMocks(); });
Alternatively, use jest.spyOn(global, 'fetch') instead of overwriting global.fetch directly—this makes restoring the original function easier.
内容的提问来源于stack exchange,提问作者LazioTibijczyk

