Currently, I am developing a Typescript React application using Vite. To test my app, I have implemented Jest and babel. An important aspect of my setup is the use of absolute paths throughout the entire application.
Interestingly, when I run tests with relative paths for images, they pass successfully. However, when I switch to absolute paths for SVG files, the tests fail.
Examining my Jest configuration:
module.exports = {
testEnvironment: 'jest-environment-jsdom',
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1',
'^@api(.*)$': '<rootDir>/src/api$1',
'^@assets(.*)$': '<rootDir>/src/assets$1',
'^@components(.*)$': '<rootDir>/src/components$1',
'^@hooks(.*)$': '<rootDir>/src/hooks$1',
'^@interfaces(.*)$': '<rootDir>/src/interfaces$1',
'^@layouts(.*)$': '<rootDir>/src/layouts$1',
'^@pages(.*)$': '<rootDir>/src/pages$1',
'^@routes(.*)$': '<rootDir>/src/routes$1',
'^@store(.*)$': '<rootDir>/src/store$1',
'^@utils(.*)$': '<rootDir>/src/utils$1',
// For svg images transformer
'^.+\\.svg$': 'jest-svg-transformer',
},
setupFilesAfterEnv: ['./jest.setup.ts'],
};
Regarding my Vite configuration:
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
'@api': path.resolve(__dirname, './src/api'),
'@assets': path.resolve(__dirname, './src/assets'),
'@components': path.resolve(__dirname, './src/components'),
'@hooks': path.resolve(__dirname, './src/hooks'),
'@interfaces': path.resolve(__dirname, './src/interfaces'),
'@layouts': path.resolve(__dirname, './src/layouts'),
'@pages': path.resolve(__dirname, './src/pages'),
'@routes': path.resolve(__dirname, './src/routes'),
'@store': path.resolve(__dirname, './src/store'),
'@utils': path.resolve(__dirname, './src/utils'),
},
},
...
My TypeScript configuration is as follows:
"baseUrl": "./src",
"paths": {
"@api/*": ["api/*"],
"@assets/*": ["assets/*"],
"@components/*": ["components/*"],
"@hooks/*": ["hooks/*"],
"@interfaces/*": ["interfaces/*"],
"@layouts/*": ["layouts/*"],
"@pages/*": ["pages/*"],
"@routes/*": ["routes/*"],
"@store/*": ["store/*"],
"@utils/*": ["utils/*"]
}
Finally, the component where I encounter the issue:
import loginIcon from '../../assets/images/privacy.svg'; //passes
import loginIcon from '@assets/images/privacy.svg'; //fails
...
<Box height={64} width={64} mb={4}>
<img src={loginIcon} width='64' height='64' />
</Box>
The reason behind this behavior is still unknown to me. It may be related to the functionality of jest-svg-transformer. I am puzzled by why it fails with absolute paths.