Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug]: unmatched capture groups in moduleNameMapper regexes are replaced with the string "undefined" instead of an empty string #14500

Closed
niklasholm opened this issue Sep 7, 2023 · 1 comment · Fixed by #14507

Comments

@niklasholm
Copy link
Contributor

Version

29.6.4

Steps to reproduce

  1. Put this in your jest configuration
const config = {
  moduleNameMapper: {
    "^@Foobar(/.*)?$": "<rootDir>/src/components/Foobar$1", // Path to any folder with an index.js
  }
}
  1. Put this in any file tested by jest
import Foobar from "@Foobar";
  1. Run a test for that file.

Expected behavior

The test should execute normally.

Actual behavior

The test will fail because jest-resolve didn't find the component

  ● Test suite failed to run

    Configuration error:

    Could not locate module @Foobar mapped as:
    C:\Users\nikho\jest-test\src\components\Foobar$1.

    Please check your configuration for these entries:
    {
      "moduleNameMapper": {
        "/^@Foobar(\/.*)?$/": "C:\Users\nikho\jest-test\src\components\Foobar$1"
      },
      "resolver": undefined
    }

This is because when the capture group (/.*)? is not matched it will get the value undefined in the object returned by String.prototype.match, and this is coerced to a string instead of replaced with an empty string, so jest-resolve will try to find the component Foobarundefined instead of Foobar. Simply adding || "" to line 442 should fix the issue.

moduleName.replace(
/\$([0-9]+)/g,
(_, index) => matches[parseInt(index, 10)],
)

Additional context

No response

Environment

System:
    OS: Windows 10 10.0.19045
    CPU: (8) x64 Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz
  Binaries:
    Node: 18.17.1 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.22.19 - ~\AppData\Roaming\npm\yarn.CMD
    npm: 10.0.0 - ~\AppData\Roaming\npm\npm.CMD
  npmPackages:
    jest: ^29.6.4 => 29.6.4
@github-actions
Copy link

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Oct 12, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant