如何模拟模块中的异步函数并让API返回抛出错误(Jest测试)
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.getHostLocationis already a mock function (set this up withjest.mock('./path-to-your-api-module')before your test suite runs). - The error you pass to
mockRejectedValueshould match what your component expects (e.g., a string message or an error object with specific properties). - This will trigger the
catchblock in your component's async handler, which should update the component state to display the error message.
内容的提问来源于stack exchange,提问作者ridermansb

