๐ big fan of this package! Ran into a subtle issue in my (unconventional) repo structure.
Problem
Consider this highly simplified and somewhat contrived example:
.
โโโ README.md
โโโ app
โย ย โโโ jest.config.js
โย ย โโโ package.json
โย ย โโโ src
โย ย โโโ index.test.js
โโโ jest.config.js
โโโ jsconfig.json
โโโ package.json
โโโ src
โย ย โโโ index.test.js
โย ย โโโ utils
โย ย โโโ some-util.js
โโโ yarn.lock
The bulk of the code lives in src
, though there's also an app
directory which functionally is its own package. However, it does share modules (and aliases) with src
. Consider this jsconfig.json
:
{
"compilerOptions": {
"paths": {
"@utils/*": ["./src/utils/*"],
"@app/*": ["./app/src/*"]
}
}
}
Both the top-level package and app
have their own set of tests and corresponding jest.config.js
files. In the top-level config, I would expect (and do correctly get!) the following moduleNameMapper
value generated by alias-hq
:
{
'^@utils/(.*)$': '<rootDir>/src/utils/$1',
'^@app/(.*)$': '<rootDir>/app/src/$1'
}
Likewise for app
, I would expect this in its config (app/jest.config.js
):
{
'^@utils/(.*)$': '<rootDir>/../src/utils/$1',
'^@app/(.*)$': '<rootDir>/../app/src/$1'
}
However, I instead get this:
{
'^@utils/(.*)$': 'src/utils/$1',
'^@app/(.*)$': 'app/src/$1'
}
Root cause
This seems to be due to the Jest plugin's implementation using path.join
:
|
return join('<rootDir>', baseUrl, path) |
When baseUrl
is ..
, join
removes the <rootDir>
segment entirely. However, in this case (I think) we always want that to exist. Paths like <rootDir>/../src/utils/$1
resolve just fine with Jest's parser.
I've created a reproduction repo matching this described case for easier testing. I also have a branch up which (from what I can tell) fixes the issue - happy to open a PR if you think this is sufficient.
Possible misconfiguration
I wasn't entirely sure how to configure alias-hq
for this sort of situation. I did the following in app/jest.config.js
:
const {
get: getModuleAliases,
config: aliasConfig,
load: loadAliasConfig,
} = require('alias-hq');
const path = require('path');
loadAliasConfig(path.resolve('../jsconfig.json'));
aliasConfig.baseUrl = '..';
module.exports = {
roots: ['<rootDir>/src'],
moduleNameMapper: getModuleAliases('jest'),
};
(I think) I had to manually point to jsconfig.json
since it's not in a standard location relative to this config. I also manually set a baseUrl
so that paths would be set relative to the parent dir. Still fairly new to this package so please let me know if there's a better / simpler way to configure this!
Happy to clarify any details - thanks!