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

react-testing-library如何测试helpers返回的bar函数是否被调用

问题原因

你之前的写法失效是因为每次调用helpers()都会生成一个全新的对象,你在断言时调用helpers().bar拿到的是新创建的mock函数,和组件渲染时从helpers()里拿到的bar不是同一个引用,自然检测不到调用记录。

正确写法

你只需要提前把bar的mock函数定义好,保存固定引用即可,修改后的测试用例如下:

import React from 'react';
import userEvent from '@testing-library/user-event';
import { screen, render } from '@testing-library/react';
import TestComponent from './TestComponent';
import { helpers } from './helpers';

jest.mock('./helpers', () => ({
  helpers: jest.fn(),
}));

test('bar is called', () => {
  // 提前定义bar的mock函数,保存固定引用
  const mockBar = jest.fn();
  helpers.mockImplementation(() => ({
    bar: mockBar,
  }));

  render(<TestComponent />);

  userEvent.click(screen.getByRole('button'));

  // 直接断言提前保存的mock函数即可
  expect(mockBar).toHaveBeenCalled();
});

可选写法

如果你不想额外定义变量,也可以从helpers的mock调用记录里取到组件渲染时生成的bar函数:

expect(helpers.mock.results[0].value.bar).toHaveBeenCalled();

这种写法的原理是helpers.mock.results会按调用顺序保存所有helpers执行的返回结果,下标0对应的就是组件渲染时第一次调用helpers返回的对象,里面的bar就是组件实际绑定到按钮点击事件的函数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 21:36:07