Skip to content

Commit

Permalink
feat: add startsWith option
Browse files Browse the repository at this point in the history
BREAKING_CHANGE
  • Loading branch information
HosseinAgha committed Oct 26, 2019
1 parent d1c1189 commit b3b9005
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 3 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,7 @@ module.exports = {
// ... other configs
}
```

## Options

- __startsWith:__ ensures that all the replaced paths (keys in the tsconfig) happen at the beginning of the path. is `true` by default.
12 changes: 11 additions & 1 deletion src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,18 @@ describe('test lib', () => {
tsconfigPathsJestMapper(path.resolve(__dirname, '../test/right-config'));
})

it('should convert paths to jest moduleNameMapper', () => {
it('should convert paths to jest moduleNameMapper when they start with pattern', () => {
const mappers = tsconfigPathsJestMapper(path.resolve(__dirname, '../test/right-config'));
expect(mappers).toEqual({
"^\\$main": "<rootDir>/src/index.ts",
"^\\$components(/?.*)": "<rootDir>/src/components$1",
"^\\$errors(/?.*)": "<rootDir>/src/errors$1",
"^@app(/?.*)": "<rootDir>/src/app$1"
})
})

it('should convert paths to jest moduleNameMapper everywhere', () => {
const mappers = tsconfigPathsJestMapper(path.resolve(__dirname, '../test/right-config'), { startsWith: false });
expect(mappers).toEqual({
"\\$main": "<rootDir>/src/index.ts",
"\\$components(/?.*)": "<rootDir>/src/components$1",
Expand Down
7 changes: 5 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ function escapeRegExp(text: string) {
return text.replace(/[-[\]{}()+?.,\\^$|#\s]/g, '\\$&');
}

export const getJestMappersFromTSConfig = (tsconfigPath: string) => {
export const getJestMappersFromTSConfig = (tsconfigPath: string, options: { startsWith: boolean } = { startsWith: true }) => {
const { config } = loadSync('', tsconfigPath);
if (!config.compilerOptions || !config.compilerOptions.paths) {
throw new Error('paths field not found in tsconfig compiler options');
Expand All @@ -28,7 +28,10 @@ export const getJestMappersFromTSConfig = (tsconfigPath: string) => {
}

const [ value ] = valueArray;
const source = escapeRegExp(key).replace(/\/\*/, "(/?.*)");
let source = escapeRegExp(key).replace(/\/\*/, "(/?.*)");
if(options.startsWith) {
source = `^${source}`;
}
const path = `<rootDir>/${value.replace(/\/?\*/, "$1")}`;
moduleNameMapper[source] = path;
}
Expand Down

0 comments on commit b3b9005

Please sign in to comment.