组件测试报错:SyntaxError: Cannot use import statement outside a module
Jest测试中Axios导入报错:SyntaxError: Cannot use import statement outside a module
我在为组件编写渲染验证测试时遇到该错误,测试代码如下:
test('Should render the movie info', () => { renderWithContext(<MovieInfo movie={mockMovies[0]} />); expect(screen.getByText('Terrifier 2')).toBeInTheDocument(); });
运行测试时触发错误:
SyntaxError: Cannot use import statement outside a module
错误源自axios的导入语句:
> 2 | import axios from 'axios'; | ^
当前jest.config.js配置:
const { compilerOptions } = require('./tsconfig.json'); const { pathsToModuleNameMapper } = require('ts-jest'); const { default: tsjPreset } = require('ts-jest'); module.exports = { transform: { ...tsjPreset.transform, '+\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2|pdf)$': 'jest-transform-stub', '^.+\.ts?$': 'ts-jest', }, moduleDirectories: ['src', 'node_modules'], moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths), setupFilesAfterEnv: ['<rootDir>/src/setupTests.ts'], transformIgnorePatterns: ['node_modules/(?!(axios)/)'], };
已安装依赖:ts-jest、@types/jest、jest-transform-stub
解决步骤
修正
transformIgnorePatterns正则
原配置的正则存在冗余语法,修改为:transformIgnorePatterns: ['node_modules/(?!axios)'],确保Jest不对axios模块跳过转换,因为axios采用ES模块语法,需要ts-jest处理。
修复
transform中的文件后缀匹配正则
原配置里'+\.(css|...)'的正则写法错误,+无匹配意义,改为:'\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2|pdf)$': 'jest-transform-stub',调整
transform规则,覆盖所有需要转换的文件
移除可能冲突的tsjPreset.transform,明确指定ts-jest处理TS/JS文件:transform: { '^.+\\.(ts|tsx|js|jsx)$': 'ts-jest', '\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2|pdf)$': 'jest-transform-stub', },检查
tsconfig.json模块配置
确保compilerOptions.module设置为CommonJS(Jest默认兼容),如果使用ESNext,需在jest.config.js中添加:module: 'ESNext', extensionsToTreatAsEsm: ['.ts', '.tsx'],兜底方案:Mock axios
若上述方法仍无效,直接在测试文件顶部Mock axios,避免实际导入引发的模块问题:jest.mock('axios', () => ({ default: jest.fn(() => Promise.resolve({ data: {} })), }));
内容的提问来源于stack exchange,提问作者SmarTv
相关产品推荐
相关产品推荐

