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

使用CRA创建React应用,测试中Axios出现网络错误求助

Fixing Axios Network Error in CRA React Tests

Let's walk through the common reasons your Axios request is throwing a network error during tests and how to fix them:

1. Your local development server isn't running during tests

When you run npm test with Create React App, Jest (the built-in test runner) doesn't spin up your development server at localhost:3000. That means there's no server listening to respond to your Axios request—hence the network error.

Solution: Mock Axios instead of making real requests

Unit tests should focus on verifying your code's logic, not hitting live APIs. Here's how to mock Axios in your test file to avoid real network calls:

import axios from 'axios';

// Mock the entire axios module so it doesn't make real requests
jest.mock('axios');

test('adds 1 + 2 to equal 3', () => {
  expect(3).toBe(3);
});

// If you want to test a function that uses Axios, here's an example setup:
test('fetches coins successfully', async () => {
  // Define mock response data
  const mockCoinData = { data: [{ id: 1, name: 'Bitcoin' }] };
  // Tell Axios's get method to return this mock data
  axios.get.mockResolvedValue(mockCoinData);

  // Call your actual function that makes the Axios request
  const result = await fetchCoins(); // Replace with your function name

  // Verify the request was sent to the correct URL
  expect(axios.get).toHaveBeenCalledWith('http://localhost:3000/coins');
  // Check that the result matches our mock data
  expect(result).toEqual(mockCoinData.data);
});

2. The Axios request is running at the top level of your test file

Looking at your code, the Axios get call is directly in the test file (not inside a test function or component). This means it runs as soon as Jest loads the file—before any tests execute, and when there’s definitely no server running to respond.

Solution: Wrap the request in reusable logic

Move the Axios call into a function that you can trigger from components or test cases, instead of running it at the file's top level:

import axios from 'axios';

// Wrap the request in a function
export const fetchCoins = async () => {
  try {
    const response = await axios.get('http://localhost:3000/coins');
    console.log(response);
    return response.data;
  } catch (error) {
    console.log(error.response);
    throw error;
  }
};

test('adds 1 + 2 to equal 3', () => {
  expect(3).toBe(3);
});

// Now you can test this function using the mock setup from the first section

3. Bonus: If you need to hit a real server (for integration tests)

If you’re writing an integration test that requires a running server, you have two options:

  • Start your development server in one terminal (npm start), then run your tests in a second terminal (npm test)
  • Use a tool like start-server-and-test to automate this: install it via npm, then add a script to your package.json like "test:integration": "start-server-and-test start http://localhost:3000 test"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:02:26