Wednesday, August 1, 2018

Configuring unit testing path aliases with Jest, Typescript and React-native


I ran into some nasty problems recently (well the latest set of them anyway) trying to run tests with the Jest setup in a react-native project. A while ago I had seen a nice Typescript feature where you can set up an alias for a path in your source code (details of that in this post and others). Having been round the block a few times over the years with "../../../../" relative paths, these path aliases felt like something of a solution.

A while after that, I started setting up some Jest unit tests, and while some worked just fine, others would fail on imports. The reason is that Jest has no clue about these path aliases that Typescript is using (although there might be an argument that something like ts-jest should relay that information). I'm not a fan of having these nice features, and then finding that you need to set them up in more than one place, but the only way I have found to fix the issue so far is using the moduleNameMapper configuration for Jest.


As an example, let's say we have an assets directory path set up in tsconfig.json as per the following snippet:

"paths":  
{  
    "@assets/*": [ "src/assets/*" ],  
},  

And remembering that we need an extra package.json file in the assets directory with the following configuration:

{ "name": "@assets" }

Then we can tell Jest about that in the jest config in our main package.json (or in jest.config.js if you went that way):

"moduleNameMapper": 
{  
    "@assets/(.*)$": "<rootDir>/src/assets/$1"  
},  

Which essentially says "for anything that begins with @assets/ substitute with the root directory of the project then src/assets and then whatever comes after" so:

@assets/images/icons/icon1.png

becomes something like

/users/example/react-native-projects/my-app/src/assets/images/icons/icon1.png

If anyone knows of a better method, and by that I mean a method where Jest uses the information in tsconfig.json, please tell me and I will update this post accordingly.

No comments: