You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何测试Get请求处理函数的.json()异常捕获分支?

How to Trigger the Catch Block in Your Async Get Function with Jest

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 03:49:10