Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
alexgleason opened this issue Apr 6, 2022 · 3 comments

Comments

@alexgleason
Copy link

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
Copy link
Author

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

@Dodobrat
Copy link

Dodobrat commented Sep 30, 2022

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.

@yang4515
Copy link

Same issue with vitest

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants