I have been using jest for unit testing in my react project (typescript). Now I have enabled path alias in webpack and tsconfig. In order to use path alias with jest, I have followed this tutorial. But I am getting this error when I run my tests:
Here is my webpack configuration to enable path alias:
alias: {
'ui': path.resolve(__dirname, 'src/framework/components/ui')
}
Here is my jest configuration to enable path alias (package.json)
"moduleNameMapper": {
"ui": "<rootDir>/src/framework/components/ui/"
}
I also tried this version from the tutorial:
"moduleNameMapper": {
"^ui/(.*)$1": "<rootDir>/src/framework/components/ui/$1"
}
Finally here is my tsconfig.json configuration:
"baseUrl": "src",
"paths": {
"ui": ["framework/components/ui"]
}
When I run my test, jest actually resolves the path alias. But it fails to pick up components exposed as default. For e.g this line:
import Button from './FormComponents/Button';
fails because 'Button' is exported as default from its module.
I hope my question makes sense. Thank you in advance for your help.
Use ts-jest
https://huafu.github.io/ts-jest/user/config/#jest-config-with-helper:
// jest.config.js
const { pathsToModuleNameMapper } = require('ts-jest/utils');
// In the following statement, replace `./tsconfig` with the path to your `tsconfig` file
// which contains the path mapping (ie the `compilerOptions.paths` option):
const { compilerOptions } = require('./tsconfig');
module.exports = {
// [...]
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths /*, { prefix: '<rootDir>/' } */ )
};
Try
"moduleNameMapper": {
"^ui/(.*)": "<rootDir>/src/framework/components/ui/$1"
}
It shouldn't have $1 in the regex as $1 is used in the replacement string to insert the captured text.
E.g. in your example, "Button" would be captured by the (.*) and then used in place of $1 in the replacement string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With