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

Jest模拟API调用返回undefined问题求助

问题:Jest模拟API返回undefined导致测试报错

我在为<App/>组件调用的API编写Jest模拟,但jest.mock返回的结果是undefined,运行测试时报错。

相关代码

App组件代码

import './App.css';
import Sidebar from './Sidebar';
import { useEffect, useState } from 'react';
import { getCount } from './api';

function App() {
  const [state, setState] = useState({
    status: 'ok',
    count: 0,
  });

  useEffect(() => {
    getCount().then((res) => setState((prevState) => ({ ...prevState, count: res })));
  }, []);

  return (
    <div className='App'>
      <Sidebar state={state} />
    </div>
  );
}

export default App;

API调用代码(返回Promise)

export function getCount() {
  return Promise.resolve(5);
}

测试代码(原报错版本)

import { render, screen } from '@testing-library/react';
import App from './App';

jest.mock('./api', () => ({
  getCount: jest.fn(() => Promise.resolve(5)),
}));

test('renders app', () => {
  render(<App />);
});

解决方案

问题核心是测试未等待异步API调用完成就结束,且未正确处理组件的状态更新。以下是修复步骤:

  1. 导入并引用mock函数
    从./api导入mock的getCount,确保能验证函数调用情况,保证mock逻辑生效。

  2. 使用异步查询或waitFor等待状态更新
    React Testing Library的waitFor或findBy*系列方法会自动等待异步操作完成,确保组件状态更新后再执行断言。

修改后的测试代码

import { render, screen, waitFor } from '@testing-library/react';
import App from './App';
import { getCount } from './api'; // 导入mock函数

jest.mock('./api', () => ({
  getCount: jest.fn(() => Promise.resolve(5)),
}));

test('renders app and fetches count correctly', async () => {
  render(<App />);

  // 等待异步状态更新,验证count是否渲染(假设Sidebar会展示count值)
  await waitFor(() => {
    expect(screen.getByText('5')).toBeInTheDocument();
  });

  // 验证mock API是否被调用
  expect(getCount).toHaveBeenCalledTimes(1);
});

补充说明

  • 若Sidebar组件未直接渲染count值,可通过getByTestId等查询方法检查组件props或内部元素的变化。
  • 确保mock函数实现正确:jest.fn(() => Promise.resolve(5))不能写错,比如遗漏箭头函数逻辑会导致返回undefined。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 04:55:16