Home > Blockchain >  Linked library breaking Jest tests
Linked library breaking Jest tests

Time:09-30

We have written a React library that we are using in another app. When I use npm link ../myLibrary, running Jest tests will fail with the following message:

TypeError: Cannot read property 'webpackChunk_my_library' of undefined

I can get around this by editing my Jest config:

"transformIgnorePatterns": [
  "../myLibrary"
],

But this produces other issues...

 Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
    1. You might have mismatching versions of React and the renderer (such as React DOM)                                                 
    2. You might be breaking the Rules of Hooks                     
    3. You might have more than one copy of React in the same app   
    See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

In Webpack, I've added aliases for React and ReactDOM and that fixes it for normal work. I try do something similar by editing the Jest config:

"moduleNameMapper": {
  "\\.(css|postcss|less)$": "identity-obj-proxy",
  "react": "<rootDir>/node_modules/react",
  "react-dom": "<rootDir>/node_modules/react-dom"
},

Now I get another issue...

TypeError: react__WEBPACK_IMPORTED_MODULE_3__.memo is not a function

I've tried variations of all of the above, but I can't figure out the right combination. In the Webpack config for my library I have this set (if it makes a difference):

externals: {
  react: 'react',
  'react-dom': 'react-dom',
},

CodePudding user response:

Turns out Jest is using regex patterns for moduleNameMapper. After changing to the following it works fine:

"transformIgnorePatterns": [
  "../myLibrary"
],
"moduleNameMapper": {
  "\\.(css|postcss|less)$": "identity-obj-proxy",
  "^react$": "<rootDir>/node_modules/react",
  "^react-dom$": "<rootDir>/node_modules/react-dom"
},
  • Related