Skip to content

[Bug]: require.resolve() with options.paths ignores moduleNameMapper #14601

@layershifter

Description

@layershifter

Version

29.7.0

Steps to reproduce

  1. Open https://stackblitz.com/edit/stackblitz-starters-7snujh
  2. Run jest in a terminal
  3. Notice failing tests

Expected behavior

Tests are simple and assert require.resolve() behavior:

it('require-resolve', () => {
  const result = require.resolve('@foo/js');

  expect(typeof result).toBe('string');
  expect(result).toMatch(/\/js\/index.js$/);
});

it('require-resolve-paths', () => {
  const paths = [__dirname];
  const result = require.resolve('@foo/js', { paths });

  expect(typeof result).toBe('string');
  expect(result).toMatch(/\/src\/\@foo\/js\/index.js$/);
});

The expectation is that both tests will pass.

Actual behavior

require-resolve-paths test is failing with:

    Message:
      Cannot resolve module '@foo/js' from paths ['/home/projects/stackblitz-starters-7snujh/packages'] from /home/projects/stackblitz-starters-7snujh/packages/require-resolve-paths.test.js

While moduleNameMapper is configured:

module.exports = {
  moduleNameMapper: {
    '@foo/js': '<rootDir>/js/index.js',
  },
}

It fails because once options.paths are used, completely different branch is used:

const {paths} = options;
if (paths) {
for (const p of paths) {
const absolutePath = path.resolve(from, '..', p);
const module = this._resolver.resolveModuleFromDirIfExists(

resolveModuleFromDirIfExists() does not check for moduleNameMapper config unlike _resolveCjsModule() (or actually resolveModule() that is used in a default scenario.

Additional context

No response

Environment

System:
    OS: Linux 5.0 undefined
    CPU: (8) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
  Binaries:
    Node: 18.18.0 - /usr/local/bin/node
    Yarn: 1.22.19 - /usr/local/bin/yarn
    npm: 9.4.2 - /usr/local/bin/npm
    pnpm: 8.6.12 - /usr/local/bin/pnpm
  npmPackages:
    jest: ^29.7.0 => 29.7.0

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions