diff --git a/CHANGELOG.md b/CHANGELOG.md index 0ce2bc5c5d9c..676e0753208a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ ### Fixes +- `[jest-resolver]` Replace unmatched capture groups in `moduleNameMapper` with empty string instead of `undefined` ([#14507](https://github.com/jestjs/jest/pull/14507)) - `[jest-snapshot]` Allow for strings as well as template literals in inline snapshots ([#14465](https://github.com/jestjs/jest/pull/14465)) - `[@jest/test-sequencer]` Calculate test runtime if `perStats.duration` is missing ([#14473](https://github.com/jestjs/jest/pull/14473)) diff --git a/packages/jest-resolve/src/__mocks__/foo/bar/index.js b/packages/jest-resolve/src/__mocks__/foo/bar/index.js new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/packages/jest-resolve/src/__tests__/resolve.test.ts b/packages/jest-resolve/src/__tests__/resolve.test.ts index 1bc9c447f190..a027d1065aab 100644 --- a/packages/jest-resolve/src/__tests__/resolve.test.ts +++ b/packages/jest-resolve/src/__tests__/resolve.test.ts @@ -561,6 +561,25 @@ describe('resolveModule', () => { expect(mockUserResolver).toHaveBeenCalled(); expect(mockUserResolver.mock.calls[0][0]).toBe('fs'); }); + + it('handles unmatched capture groups correctly', () => { + const resolver = new Resolver(moduleMap, { + extensions: ['.js'], + moduleNameMapper: [ + { + moduleName: './__mocks__/foo$1', + regex: /^@Foo(\/.*)?$/, + }, + ], + } as ResolverConfig); + const src = require.resolve('../'); + expect(resolver.resolveModule(src, '@Foo')).toBe( + require.resolve('../__mocks__/foo.js'), + ); + expect(resolver.resolveModule(src, '@Foo/bar')).toBe( + require.resolve('../__mocks__/foo/bar/index.js'), + ); + }); }); describe('resolveModuleAsync', () => { diff --git a/packages/jest-resolve/src/resolver.ts b/packages/jest-resolve/src/resolver.ts index 7f378e859a19..359acc774faf 100644 --- a/packages/jest-resolve/src/resolver.ts +++ b/packages/jest-resolve/src/resolver.ts @@ -439,7 +439,7 @@ export default class Resolver { ? (moduleName: string) => moduleName.replace( /\$([0-9]+)/g, - (_, index) => matches[parseInt(index, 10)], + (_, index) => matches[parseInt(index, 10)] || '', ) : (moduleName: string) => moduleName; }