Unable to use with Jest: `SyntaxError: Cannot use import statement outside a module`
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.
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
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.
Same issue with vitest