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

如何模拟模块中的异步函数并让API返回抛出错误(Jest测试)

How to Mock a Rejected Promise for getHostLocation in Jest

To make api.getHostLocation return a rejected promise (simulating a failed request), you need to use mockRejectedValue (or mockRejectedValueOnce) instead of mockResolvedValue. Your previous attempt used mockResolvedValue with an empty function, which resolves the promise to that function instead of triggering a failure.

Here's the fixed approach:

Step 1: Mock the Rejected Promise

Replace your commented line with this code to force the API call to fail:

// Mock the API method to reject with an error
api.getHostLocation.mockRejectedValue(new Error('Request failed'));

If you only want this failure to happen once for this specific test case, use:

api.getHostLocation.mockRejectedValueOnce(new Error('Request failed'));

Step 2: Wait for Async Operations to Settle

After simulating the form submit, ensure you wait for the rejected promise to propagate through your component. You already have await fetchMock.flush(); which should handle network-related async work, but adding await wrapper.update() ensures the component re-renders with the error state.

Full Test Case Example

Here's your complete test with the fix integrated:

it('should display error if request fails', async () => { 
  const preventDefault = jest.fn(); 
  const urlCalled = `${apiHost}/json/aaac.co`; 
  const wrapper = mount(<WebsiteLocationSearch />); 

  // Mock API failure
  api.getHostLocation.mockRejectedValue(new Error('Failed to load location'));

  // Simulate user input and form submission
  wrapper.find('#host').instance().value = 'aaac.co'; 
  wrapper.simulate('submit', { preventDefault }); 

  // Wait for async operations to complete
  await fetchMock.flush(); 
  await wrapper.update(); 

  // Verify error is displayed
  expect(wrapper.find('.error-message').exists()).toBe(true);
  expect(wrapper.find('.error-message').text()).toContain('Failed to load location');
});

Key Notes:

  • Ensure api.getHostLocation is already a mock function (set this up with jest.mock('./path-to-your-api-module') before your test suite runs).
  • The error you pass to mockRejectedValue should match what your component expects (e.g., a string message or an error object with specific properties).
  • This will trigger the catch block in your component's async handler, which should update the component state to display the error message.

内容的提问来源于stack exchange,提问作者ridermansb

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:05:59