我有一个使用 webpacker 的 Rails 5 应用程序,带有一个文件 app/javascript/packs/components/module_one.js,我正在尝试用 Jest 进行测试。此文件包含对 .js.erb 文件的导入,如下所示:
// app/javascript/packs/components/module_one.js
import ModuleTwo from './module_two.js.erb'
// ...
module_two.js.erb 包含以下内容:
// app/javascript/packs/components/module_two.js.erb
import ModuleOne from './module_one'
// ...
在运行 webpack-dev-server 时,一切都按预期工作,但是当我尝试运行 yarn test 时,它会抱怨以下错误:
FAIL app/javascript/test/module_one.test.js
● Test suite failed to run
/path/to/module_two.js.erb:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import ModuleOne from './module_one'
^^^^^^
SyntaxError: Unexpected token import
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:306:17)
at Object.<anonymous> (app/javascript/packs/components/module_one.js:1:745)
at Object.<anonymous> (app/javascript/test/module_one.test.js:1:124)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 2.545s
Ran all test suites.
error Command failed with exit code 1.
所以看起来 module_two.js.erb 文件没有从 ES6 正确转换,因为当我删除 module_one.js 的第一行时,它不再抱怨了。
这是我当前的设置:
// .babelrc
{
"presets": [
["env", {
"modules": false,
"targets": {
"browsers": "> 1%",
"uglify": true
},
"useBuiltIns": true
}]
],
"plugins": [
"syntax-dynamic-import",
["transform-class-properties", { "spec": true }]
],
"env": {
"test": {
"plugins": ["transform-es2015-modules-commonjs"]
}
}
}
// package.json
{
// ...
"devDependencies": {
"babel-jest": "^21.0.2",
"jest": "^21.0.2",
"regenerator-runtime": "^0.11.0",
"webpack-dev-server": "^2.7.1"
},
"scripts": {
"test": "jest"
},
"jest": {
"roots": [
"<rootDir>/app/javascript/test"
],
"moduleDirectories": [
"<rootDir>/node_modules"
],
"moduleFileExtensions": [
"js",
"jsx",
"erb"
],
"transform": {
"^.+\\.jsx?$": "babel-jest",
"ˆ.+\\.jsx?.erb": "rails-erb-loader"
}
}
}