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

React Testing Library中Mock Axios时出现toString读取undefined的TypeError

解决 TypeError: Cannot read properties of undefined (reading 'toString') 问题

常见原因及修复方案

1. 对齐Axios Mock返回结构与组件预期

组件中大概率是从Axios响应的response.data取值并调用toString(),若mock未返回完整响应结构,会导致response或response.data为undefined。

示例组件代码逻辑:

axios.get('/api/data').then(response => {
  const value = response.data.toString();
  // ...其他业务逻辑
})

错误mock方式(直接返回数据):

axios.get.mockImplementation(() => Promise.resolve('some data'));

正确mock方式(返回完整响应结构):

axios.get.mockImplementation(() => 
  Promise.resolve({ data: 'some data' })
);

2. 确保Mock覆盖组件实际调用的Axios方法

若组件使用自定义Axios实例而非全局axios,测试时需mock对应实例:

// 组件内代码
import axios from './myAxiosInstance';
axios.get('/api/data');

测试文件中对应mock:

import axios from './myAxiosInstance';
jest.mock('./myAxiosInstance');

axios.get.mockImplementation(() => 
  Promise.resolve({ data: 'valid data' })
);

3. 完善异步测试的等待逻辑

测试未正确等待异步请求完成时,组件可能在响应返回前渲染,导致取值时为undefined。需用async/await或waitFor处理异步:

test('组件渲染正常', async () => {
  render(<YourComponent />);
  // 等待异步请求完成及组件更新
  await waitFor(() => expect(screen.getByText('目标文本')).toBeInTheDocument());
});

4. 检查组件错误分支处理

若请求失败,组件未处理catch逻辑可能导致错误状态下变量为undefined。可mock失败场景验证:

axios.get.mockImplementation(() => Promise.reject(new Error('请求失败')));

确保组件在错误状态下不会触发toString()调用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 06:30:01