react-movable
react-movable copied to clipboard
React Movable makes it hard to write tests in Next.js (with Jest)
When including this library in a React component using Next.js, this error appears:
/home/my_app/node_modules/react-movable/lib/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import List from './List.js';
SyntaxError: Cannot use import statement outside a module
This hadn't happened to me with any of the many other libraries I had imported in the frontend of my project.
To be honest I'm not sure what would be the solution here. Maybe re-arrange the way files are exported/imported inside the library.
Current Workaround
In my jest.config.mjs file, I changed the way the config is exported. Note that in Next.js the convention is to use nextJest to generate the configuration object, and to export an async function.
import nextJest from 'next/jest.js';
const createJestConfig = nextJest({
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
dir: './',
});
// Add any custom config to be passed to Jest
/** @type {import('jest').Config} */
const config = {
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
testEnvironment: "jest-environment-jsdom"
};
async function jestConfig(...args) {
const nextJestConfig = await createJestConfig(config)(...args)
// HERE, don't ignore react-movable when transforming files.
nextJestConfig.transformIgnorePatterns = nextJestConfig.transformIgnorePatterns.map(pattern => {
if (pattern === '/node_modules/') {
return '/node_modules(?!/react-movable)/'
}
return pattern
})
return nextJestConfig
}
export default jestConfig
Then run Jest and it works.
I faced the same issue when I was running the test case using Jest with Storybook.
Simply adding "transformIgnorePatterns": ["/node_modules(?!/react-movable)/"] in jest configuration in Package.json solved my problem.
Jest is just difficult with pure ESM modules. I recommend using vitest. @kunalphaltankar workaround is also fine.