Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use path alias in a react project with Typescript + Jest

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:

enter image description here

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.

like image 962
TheSoul Avatar asked Jun 28 '18 10:06

TheSoul


2 Answers

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>/' } */ )
};
like image 156
Daniel Pérez Avatar answered Sep 22 '22 03:09

Daniel Pérez


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.

like image 31
jeznag Avatar answered Sep 20 '22 03:09

jeznag