Jest - 无法从“src/components/MyComponent.test.tsx”中找到模块“@lib/components”

问题描述 投票:0回答:1

我正在使用一个名为

@lib/components
的第三方组件库,并且我尝试编写一个测试
MyComponent.test.tsx
,如下所示:

import * as ComponentsLib from '@lib/components';

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

  return { view };
};

jest
  .spyOn(ComponentsLib, 'Comp1')
  .mockImplementation(() => (
    <div data-testid='test'>{'test'}</div>
  ));

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

但是,我收到以下错误:

Cannot find module '@lib/components' from 'src/components/MyComponent.test.tsx'

那么我如何从该组件库中模拟

Comp1
的实现?

javascript reactjs jestjs
1个回答
0
投票

听起来你正在使用开玩笑不知道的导入别名(

@lib
指的是什么路径?我假设你的项目中没有名为
@lib/components
的npm模块?)

此问题的解决方案位于 moduleNameMapper

下的 jest.config.js 文件中
  "moduleNameMapper": {
    "^@lib$": "<rootDir>/src$1",
  } 
© www.soinside.com 2019 - 2024. All rights reserved.