module-name-mapper-helper.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536
  1. const localResolve = require('./local-resolve-helper')
  2. /**
  3. * Applies the moduleNameMapper substitution from the jest config
  4. *
  5. * @param {String} source - the original string
  6. * @param {String} filePath - the path of the current file (where the source originates)
  7. * @param {Object} jestConfig - the jestConfig holding the moduleNameMapper settings
  8. * @returns {String} path - the final path to import (including replacements via moduleNameMapper)
  9. */
  10. module.exports = function applyModuleNameMapper (source, filePath, jestConfig = {}) {
  11. if (!jestConfig.moduleNameMapper) return source
  12. // Extract the moduleNameMapper settings from the jest config. TODO: In case of development via babel@7, somehow the jestConfig.moduleNameMapper might end up being an Array. After a proper upgrade to babel@7 we should probably fix this.
  13. const module = Array.isArray(jestConfig.moduleNameMapper) ? jestConfig.moduleNameMapper : Object.entries(jestConfig.moduleNameMapper)
  14. const importPath = module
  15. .reduce((acc, [regex, replacement]) => {
  16. const matches = acc.match(regex)
  17. if (matches === null) {
  18. return acc
  19. }
  20. return replacement.replace(
  21. /\$([0-9]+)/g,
  22. (_, index) => matches[parseInt(index, 10)]
  23. )
  24. }, source)
  25. return localResolve(
  26. filePath,
  27. importPath
  28. )
  29. }