我正在使用一个名为
@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
的实现?
听起来你正在使用开玩笑不知道的导入别名(
@lib
指的是什么路径?我假设你的项目中没有名为@lib/components
的npm模块?)
此问题的解决方案位于 moduleNameMapper
下的 jest.config.js 文件中 "moduleNameMapper": {
"^@lib$": "<rootDir>/src$1",
}