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

Jest+React Testing Library单元测试中Axios导入报错求助

React单元测试中Axios导入错误排查

在编写React组件单元测试时,import axios from 'axios';行出现Axios相关错误,以下是可能的原因及解决方法,结合你提供的代码分析:

相关代码

React组件代码(AwaitAsync2)

import { useState, useEffect } from 'react';
import axios from 'axios'; // 你提供的代码中缺失这行导入

const AwaitAsync2 = () => {
  const [posts, setPosts] = useState(null);

  useEffect(() => {
    postApi();
  }, []);

  const postApi = async () => {
    const {data} = await axios.get('https://jsonplaceholder.typicode.com/posts');
    setPosts(data);
  }
  return (
    <div>
      <h2>Await Async</h2>
      {
        posts !== null && (<div data-testid="post-list">
          {
            posts.map((item, index) => {
              return <div key={index}>
                <h3>{item.title}</h3>
                <p>{item.body}</p>
              </div>
            })
          }
        </div>)
      }
    </div>
  )
}

export default AwaitAsync2;

单元测试代码

import { render, screen } from "@testing-library/react";
import AwaitAsync2 from "./aa2";
import axios from 'axios';

jest.mock('axios'); // 推荐添加mock,避免真实网络请求

describe("Async Await 2 testing", () => {
  it("API Testing", async () => {
    // 模拟axios返回数据
    axios.get.mockResolvedValue({
      data: [
        { title: "测试标题", body: "测试内容" }
      ]
    });
    
    render(<AwaitAsync2 />);
    const postList = await screen.findByTestId("post-list");
    expect(postList).toBeInTheDocument();
  });
});

错误原因及解决方法

  • 组件缺失Axios导入:你提供的组件代码中没有写import axios from 'axios';,运行时会报axios is not defined,测试时自然会在执行环节触发错误。解决方法:在组件顶部添加Axios的导入语句。
  • Axios未安装:如果项目依赖中没有axios包,无论是开发环境还是测试环境都会找不到模块。解决方法:执行npm install axios或yarn add axios安装依赖。
  • 测试环境未正确处理Axios:如果使用Jest等测试框架,未对Axios进行mock会导致真实网络请求,可能干扰测试结果(虽不是导入错误直接原因,但会影响测试稳定性)。解决方法:添加jest.mock('axios')并模拟get方法的返回值,避免真实请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 11:15:37