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

Next14 + Jest测试useFormState组件出现TypeError问题求助

解决Jest测试Next.js 14 useFormState时的TypeError问题

错误根源

useFormState 是Next.js 14为Server Actions配套提供的扩展API,并非React 18原生react-dom包的内置方法。在Jest测试环境中,直接运行依赖该钩子的组件时,会因找不到对应方法或返回值不可迭代报错:

TypeError: (0 , _reactdom.useFormState) is not a function or its return value is not iterable

解决方案

1. 正确Mock useFormState方法

在你的测试文件顶部添加mock,确保返回一个可迭代的数组(与useFormState的实际返回结构一致:[状态对象, 处理函数]):

// 测试文件顶部
jest.mock('react-dom', () => ({
  ...jest.requireActual('react-dom'),
  // 替换initialState为你的组件实际使用的初始状态
  useFormState: jest.fn(() => [{ message: '' }, jest.fn()]),
}));

如果需要在不同测试用例中动态修改返回值,可以在测试用例内部更新mock:

it('handles form submission state', () => {
  const mockUseFormState = jest.requireMock('react-dom').useFormState;
  mockUseFormState.mockReturnValueOnce([{ message: '提交成功' }, jest.fn()]);
  
  render(<FormComponent />);
  expect(screen.getByText('提交成功')).toBeInTheDocument();
});

2. 确保使用Next.js官方Jest预设

如果你手动配置了Jest,必须使用next/jest预设来处理Next.js的专属API和客户端组件指令。修改jest.config.js:

const nextJest = require('next/jest');

const createJestConfig = nextJest({
  dir: './', // 你的Next.js项目根目录
});

const config = {
  testEnvironment: 'jest-environment-jsdom',
  // 其他Jest配置(如setupFilesAfterEnv等)
};

module.exports = createJestConfig(config);

3. 检查组件导入与客户端指令

确认你的组件已添加'use client'指令(因为useFormState只能在客户端组件中使用),且导入路径正确:

'use client';
import { useFormState } from 'react-dom';
// 其他导入和组件逻辑

常见错误点排查

  • 未mockuseFormState:直接测试会导致React DOM找不到该方法
  • Mock返回值不符合要求:必须返回一个包含状态和函数的数组,否则会触发"不可迭代"错误
  • 未使用Next.js Jest预设:无法正确解析Next的扩展API和客户端组件标识

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 14:05:21