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

Jest测试报错:无法找到'@lib/components'模块,如何Mock组件?

解决@lib/components模块找不到问题并正确Mock Comp1组件

你的错误是因为Jest在测试环境中无法解析@lib/components这个第三方模块,直接用spyOn无法生效,需要先Mock整个模块,再指定Comp1的实现,以下是两种可行方案:

方案一:保留其他组件原有实现,仅Mock Comp1

这种方式适合你需要用到库中其他组件的真实实现,只替换Comp1的场景:

// 先Mock整个模块,保留其他组件的原有逻辑
jest.mock('@lib/components', () => ({
  ...jest.requireActual('@lib/components'),
  Comp1: jest.fn(() => <div data-testid='test'>test</div>)
}));

import * as ComponentsLib from '@lib/components';
import { render, screen } from '@testing-library/react';
import MyComponent from './MyComponent';

const setup = () => {
  render(<MyComponent />);
};

it('renders correctly', () => {
  setup();
  expect(screen.queryByTestId('test')).toBeTruthy();
  // 可选:验证Comp1组件是否被调用
  expect(ComponentsLib.Comp1).toHaveBeenCalled();
});

方案二:完全Mock模块,仅暴露需要的Comp1

如果你的测试只关心Comp1,不需要库中其他组件,可直接简化Mock:

jest.mock('@lib/components', () => ({
  Comp1: jest.fn(() => <div data-testid='test'>test</div>)
}));

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

const setup = () => {
  render(<MyComponent />);
};

it('renders correctly', () => {
  setup();
  expect(screen.queryByTestId('test')).toBeTruthy();
});

关键说明

之前的spyOn写法失效的核心原因是:Jest找不到未被Mock的@lib/components模块,必须先通过jest.mock让Jest识别该模块,才能对其中的组件进行Mock或监听调用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 03:52:14