Jest "Could not locate module" if any dependency has "src" in path

7.1k Views Asked by At

In my react app, I am importing a module as follows:

import { isValidAddress } from 'orbit-db';

Some dependency of isValidAddress requires multicodec/src/base-table (see this line).

However, jest gives the following error:

Configuration error:

Could not locate module multicodec/src/base-table mapped as:
/Users/h/Documents/code/orbit-db-time-machine/src/base-table.

Please check your configuration for these entries:
{
  "moduleNameMapper": {
    "/src\/(.*)$/": "/Users/h/Documents/code/orbit-db-time-machine/src/$1"
  },
  "resolver": null
}

I think that this is happening because the jest dependency rule "/src\/(.*)$/" is re-writing all paths with src in them to <rootDir>/src, even if they come from a npm module.

I tried to fix this by adding the following config to my package.json:

"jest": {
  "moduleNameMapper": {
    "/multicodec\/(.*)$/": "<rootDir>/node_modules/multicodec/$1"
  }
}

However, this did not change the error. The only way I have been able to remove the error is by removing my import statement - however, this is required in my code.

Note: The code works when run from my react app, it only breaks when I run jest.

2

There are 2 best solutions below

0
On BEST ANSWER
1
On

I remember coming across a similar problem when using the KY library in my React project with Jest. You might have to also use transformIgnorePatters to overcome this.

There was an issues thread where they discussed this in the KY repo that you might also find helpful, although some of the solutions are very specific to that project: https://github.com/sindresorhus/ky/issues/170