I have two test files that both use import. One of them passes, the other throws an error:
node_modules/@storybook/addon-docs/blocks.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import deprecate from 'util-deprecate';
^^^^^^
SyntaxError: Cannot use import statement outside a module
> 1 | import { DocsPage, DocsContainer } from '@storybook/addon-docs/blocks';
I've got Jest configured like so:
module.exports = {
collectCoverageFrom: ['**/*.{js,jsx,ts,tsx}', '!**/*.d.ts', '!**/node_modules/**'],
coverageThreshold: {
global: {
branches: 80,
functions: 80,
lines: 80,
statements: -10,
},
},
moduleNameMapper: {
'^@app/(.*)$': '<rootDir>/$1',
'^@components/(.*)$': '<rootDir>/components/$1',
'^@graphql/(.*)$': '<rootDir>/graphql/$1',
'^@lib/(.*)$': '<rootDir>/lib/$1',
},
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
testPathIgnorePatterns: [
'<rootDir>/node_modules/',
],
transform: {
'^.+\\.(js|jsx|ts|tsx)$': ['babel-jest', { presets: ['next/babel'] }],
},
transformIgnorePatterns: ['/node_modules/'],
};
I'm completely baffled at how one file can run fine while another can't. If someone could point me in the right direction that would be much appreciated.
Jest 27.x.x has become stricter in it's implementation.
I had a similar situation when I used a markdown npm package.
Try changing:
transformIgnorePatterns: ['/node_modules/'],
to:
transformIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>/node_modules/util-deprecate'],
Jest has this on their website where they explain how this issue can crop up.
And here's an explanation of the issue copied verbatim with the important bits highlighted:
Sometimes it happens (especially in React Native or TypeScript projects) that 3rd party modules are published as untranspiled. Since all files inside node_modules are not transformed by default, Jest will not understand the code in these modules, resulting in syntax errors. To overcome this, you may use
transformIgnorePatternsto allow transpiling such modules.