react-sticky-box icon indicating copy to clipboard operation
react-sticky-box copied to clipboard

Unable to use with Jest: `SyntaxError: Cannot use import statement outside a module`

Open alexgleason opened this issue 3 years ago • 3 comments

I added this module to my project and it works, but tests began to fail:

    Details:

    /home/alex/Projects/soapbox-fe/node_modules/react-sticky-box/dist/index.js:2
    import React, { useEffect, useRef, useState } from "react";
    ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      1 | import classNames from 'classnames';
      2 | import React from 'react';
    > 3 | import StickyBox from 'react-sticky-box';
        | ^
      4 |
      5 | const Layout: React.FC = ({ children }) => (
      6 |   <div className='sm:py-4 relative pb-36'>

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
      at Object.<anonymous> (app/soapbox/components/ui/layout/layout.tsx:3:1)

Apparently Jest expects modules to be in CJS, and it simply will not work with ESM.

alexgleason avatar Apr 06 '22 15:04 alexgleason

As a temporary workaround I added this to jest.config.js:

  transformIgnorePatterns: [
    '/node_modules/(?!(react-sticky-box)/)',
  ],

That way Jest will transform it with babel-jest. Same idea as here: https://jestjs.io/docs/tutorial-react-native#transformignorepatterns-customization

alexgleason avatar Apr 06 '22 16:04 alexgleason

Had an issue with other packages failing when I applied @alexgleason 's solution. So I came up with this:

Step 1: create __mocks__ folder in root directory Step 2: add react-sticky-box.js file Step 3: inside add

function useStickyBox() {
  return;
}
function StickyBox({ children }) {
  return children;
}

export default StickyBox;
export { useStickyBox };

Step 4: in package.json add the jest config (or other types of config)

"jest": {
    "moduleNameMapper": {
      "react-sticky-box": "<rootDir>/__mocks__/react-sticky-box.js",
      "react-pdf/dist/esm/entry.webpack": "react-pdf",
      "swiper": "<rootDir>/__mocks__/swiper.js"
    }
  }

As you can see it also worked for other packages like Swiper v8+.

Hope this helps.

Dodobrat avatar Sep 30 '22 08:09 Dodobrat

Same issue with vitest

yang4515 avatar Feb 27 '24 08:02 yang4515