Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 373
Hannes Hertach Avatar asked Oct 12 '19 23:10

Hannes Hertach


2 Answers

This was a bug and has been fixed: https://github.com/facebook/create-react-app/issues/7818

like image 136
Hannes Hertach Avatar answered Oct 24 '22 07:10

Hannes Hertach


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

like image 23
Braedon Avatar answered Oct 24 '22 07:10

Braedon