Test an .js.erb file with Rails + Webpacker + Jest

916 views Asked by At

I have a Rails 5 app which uses webpacker, with a file app/javascript/packs/components/module_one.js which I'm trying to test with Jest. This file contains an import to an .js.erb file as follows:

// app/javascript/packs/components/module_one.js

import ModuleTwo from './module_two.js.erb'

// ...

module_two.js.erb contains the following:

// app/javascript/packs/components/module_two.js.erb

import ModuleOne from './module_one'

// ...

While running webpack-dev-server everything works as expected, but when I try to run yarn test, it complains with the following error:

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.

So it seems like the module_two.js.erb file is not being transformed properly from ES6, because when I remove the first line of module_one.js, it doesn't complain anymore.

Here is my current setup:

// .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"
    }
  }
}
1

There are 1 answers

1
Elkhan  Mamedov On

In case someone else bumps into this. Your .babelrc seems to be missing "es2015" preset. Here is well explained about this and other issues configuring JS testing with Rails + Webpacker.