Working with Nrwl using a monorepo setup with multiple libraries allows to map short names to import modules based on absolute path, which in turn helps moving files around the module without affecting the client importing the module.
To map these files you need to configure path in tsconfig.json as follows:
so you can
but Jest will not recognise the mapping in tsconfig.json. and will fail
FAIL /Users/.../work/bcapp/apps/app-api/e2e/accounts/create-accounts.e2e-spec.ts
● Test suite failed to run
Cannot find module 'components/Name' from 'index.js'
1 | import { JwtStrategy } from './jwt.strategy';
2 | import { LocalStrategy } from './local.strategy';
> 3 | import AccountEntity from '@app/app-data';
| ^
4 | import { SessionSerializer } from './session.serializer';
5 | import {
6 | Form,
at Resolver.resolveModule (../../../../../../../usr/local/lib/node_modules/jest/node_modules/jest-resolve/build/index.js:221:17)
at Object.<anonymous> (/Users/.../bcapp/apps/app-api/src/auth/auth.module.ts:3:1)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 0.542s
Ran all test suites related to changed files.
So another configuration is required in the file jest-e2e.json
for understanding the path configuration above is important to know the project folder structure:
Note
pay attention to the transformation you need to take from “tsconfig path format” to “jest moduleNameMapper format”
"@app/app-data": ["libs/app-data/src/index.ts"],
"^@app/app-data$": "<rootDir>/../../../libs/app-data/src/index.ts",
- the key/value of jest is based on regular expression, first add the ^ char to the begining of the key, next add $ to the end fo the key
- for the value you need to remove the array that wraps the path
- <rootDir> will be the e2e folder, so I required to go 3 levels up in the directory to reach the root of the project and from there I used the physical path of the module
References
- Jest rootDir – https://jest-bot.github.io/jest/docs/configuration.html#rootdir-string
- Jest moduleNameMapper – https://jestjs.io/docs/en/configuration#modulepaths-arraystring
- ts-jest configurations – https://kulshekhar.github.io/ts-jest/user/config/
- Does not resolve path from tsconfig.js ‘paths’ option. #414 –https://github.com/kulshekhar/ts-jest/issues/414