SyntaxError: Cannot use import statement outside a module
在运行单测过程中一直失败,控制台报错 SyntaxError: Cannot use import statement outside a module。
仔细查看报错解决提示: Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
大致意思就是:jest 没办法转换文件。jest 是不支持ES6语法转换的,因此我们需要修改配置文件,跳过ES6 语法转换。
此类问题是因为引入的模块使用了ES语法,而jest默认是不支持ES语法的。
有两种解决思路: 1、使用babel, 自定义babel配置, jest自动使用babel做语法转换。但是又因为jest默认会忽略'node_modules', 即'node_modules'下的内容不会做语法转换。解决方法为在jest配置中添加‘transformIgnorePatterns’属性:
{
"transformIgnorePatterns": [
"node_modules/(?!(react-native|react-native-button)/)"
]
}
2、在 jest 引用对应文件处引用js 文件。
moduleNameMapper: {
'^axios$': '<rootDir>/node_modules/axios/dist/axios.min.js',
},