Resolving modules via Browser Field with Typescript and Jest code coverage

Tarun Kalra
1 min readApr 9, 2020

Step 1: Add browser field in the package.json

{
name: "project-A",
versions: "1.0.0",
main: "index.js",
browser: {}
...
}

Step 2: Add the paths to resolve the modules

{
name: "project-A",
versions: "1.0.0",
main: "index.js",
browser: {
"PATH_A": "<rootDir>/src/<PATH_A>",
"PATH_B": "<rootDir>/src/<PATH_B>",
"PATH_C": "<rootDir>/src/<PATH_C>",
"PATH_D": "<rootDir>/src/<PATH_D>",
...
}

...
}

Step 3: Add the baseUrl property in the existing tsconfig.json

{
compilerOptions: {
"outDir": "public/dist",
"module": "commonjs",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": true,
"rootDir": "src",
"baseUrl": "src/"
}
}

Step 3: Test the module in the project files by importing the modules from the directory we added in browser field.

// index.js
import {setup} from 'PATH_A/store/setup';

Ehh……

But I am not able to see the code coverage after this.

Yes, these changes will resolve the modules in your project but will not show the updated coverage on running test cases with jest.

To get the updated coverage report, we need to add the property in jest config.

{
name: "project-A",
versions: "1.0.0",
main: "index.js",
browser: {}
...
"jest": {
"moduleNameWrapper": {
"^PATH_A/(.*)$": "<rootDir>/src/<PATH_A>$1",
"^
PATH_B/(.*)$": "<rootDir>/src/<PATH_B>$1",
"^
PATH_C/(.*)$": "<rootDir>/src/<PATH_C>$1",
"^
PATH_D/(.*)$": "<rootDir>/src/<PATH_D>$1",
...
},

...
}
}

My Name is Tarun Kalra. I am a Sr. Frontend Developer at PublicisSapient
If you enjoyed this article, please clap n number of times and share it!
Thanks for your time.

--

--