[英]React: Jest configuration Issue with Path Aliases
I have set up a React custom boilerplate and it uses Webpack 5, TypeScript and other libs.我已经设置了一个 React 自定义样板,它使用了 Webpack 5、TypeScript 和其他库。 I am trying to set up Jest but I am getting an error when the test runs that
Cannot find module 'utils/constants' from 'src/App.tsx
.我正在尝试设置 Jest,但是当测试运行时出现错误,
Cannot find module 'utils/constants' from 'src/App.tsx
。
It is because of Path Aliases, I guess but I am not sure how to fix this.这是因为路径别名,我猜但我不知道如何解决这个问题。 Can anyone please help me here?
任何人都可以在这里帮助我吗? Thanks
谢谢
I am using tsconfig-paths-webpack-plugin
for Path Aliases.我正在使用
tsconfig-paths-webpack-plugin
作为路径别名。
webpack.config.js
module.exports = {
entry: path.resolve(__dirname, '..', './src/index.tsx'),
resolve: {
plugins: [new TsconfigPathsPlugin()],
.......
}
.......
}
tsconfig.json
{
"compilerOptions": {
.........
"baseUrl": "./src",
"paths": {
"components/*": ["./components/*"],
"styles/*": ["./styles/*"],
"utils/*": ["./utils/*"]
}
}
.........
}
jest.config.js
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['@testing-library/jest-dom/extend-expect'],
moduleNameMapper: {
'\\.(css|less|scss|sss|styl)$': '<rootDir>/node_modules/identity-obj-proxy'
}
};
App.tsx
import { APP_NAME } from 'utils/constants';
export const App = () => (
<h1> {APP_NAME} </h1>
);
App.test.tsx
import { screen, render } from '@testing-library/react';
import { App } from './App';
describe('App Component', () => {
it('should have React Project text', () => {
render(<App />);
expect(screen.getByText('React Project')).toBeTruthy();
});
});
Error错误
FAIL src/App.test.tsx
Test suite failed to run
Cannot find module 'utils/constants' from 'src/App.tsx'
Require stack:
src/App.tsx
src/App.test.tsx
However, Jest was able to find: 'utils/constants.ts'
You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['js', 'jsx', 'ts', 'tsx', 'json', 'node'].
I added the following configs in jest.config.js
and it worked:我在
jest.config.js
添加了以下配置并且它起作用了:
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['@testing-library/jest-dom/extend-expect'],
moduleNameMapper: {
'\\.(css|less|scss|sss|styl)$': '<rootDir>/node_modules/identity-obj-proxy',
'^components(.*)$': '<rootDir>/src/components$1',
'^styles(.*)$': '<rootDir>/src/styles$1',
'^utils(.*)$': '<rootDir>/src/utils$1'
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.