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

Jest Mock React Hook Form setValue未检测到调用:如何验证Hook内调用?

如何正确Mock react-hook-form的setValue方法以验证自定义Hook中的调用

你的测试代码里mock setValue 的方式有误,导致mockSetValue从未被触发。问题出在这行代码:

setValue: () => mockSetValue

这里你返回的是一个匿名函数,而不是直接把mockSetValue赋值给setValue。当useTest里调用setValue()时,实际执行的是这个匿名函数,但它只是返回mockSetValue本身,并没有调用这个mock函数,所以断言会失败。

正确的Mock方式有两种:

方式一:直接赋值mock函数给setValue

修改测试文件中的jest.mock部分,直接将mockSetValue赋值给setValue:

import useTest from './useTest';
import { useFormContext } from 'react-hook-form';
import { renderHook } from '@testing-library/react-hooks';

describe('test', () => {
  const mockSetValue = jest.fn();
  
  jest.mock('react-hook-form', () => ({
    ...jest.requireActual('react-hook-form'),
    useFormContext: () => ({
      setValue: mockSetValue // 直接赋值mock函数
    })
  }));

  it('test setValue mock', async () => {
    renderHook(() => useTest());

    expect(mockSetValue).toHaveBeenCalled();
  });
});

方式二:使用jest.spyOn动态mock(更灵活)

如果需要在不同测试用例中使用不同的mock行为,推荐用jest.spyOn来mockuseFormContext,这样可以针对单个测试用例配置mock:

import useTest from './useTest';
import * as reactHookForm from 'react-hook-form';
import { renderHook } from '@testing-library/react-hooks';

describe('test', () => {
  it('test setValue mock', async () => {
    const mockSetValue = jest.fn();
    // 用spyOn mock useFormContext的返回值
    jest.spyOn(reactHookForm, 'useFormContext').mockReturnValue({
      setValue: mockSetValue
    });

    renderHook(() => useTest());

    expect(mockSetValue).toHaveBeenCalled();
  });
});

两种方式都能确保useTest中调用的setValue就是你定义的mock函数,从而正确验证它的调用情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 14:55:15