I am crating a Typescript React app with vite. I'm using Jest and babel to run tests for my react app. I have set up absolute paths to sue throughout the application.
When I try to run my test using relative path for the image it passes. However, when using absolute paths for svg file it fails.
My jest config:
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'],
};
My Vite config:
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 TS config:
"baseUrl": "./src",
"paths": {
"@api/*": ["api/*"],
"@assets/*": ["assets/*"],
"@components/*": ["components/*"],
"@hooks/*": ["hooks/*"],
"@interfaces/*": ["interfaces/*"],
"@layouts/*": ["layouts/*"],
"@pages/*": ["pages/*"],
"@routes/*": ["routes/*"],
"@store/*": ["store/*"],
"@utils/*": ["utils/*"]
}
And finally the component where I'm using it:
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>
I have no idea why this is happening, I guess it could be a jest-svg-transformer feature. But not sure why it fails using absolute paths
CodePudding user response:
The problem here is your moduleNameMapper
value for @assets
resolves to <rootDir>/src/assets$1
instead of jest-svg-transformer
in your jest.config.js
.
Try adding an alias for '^@assets/images(.*)$': 'jest-svg-transformer'