LoginSignup
23
13

More than 5 years have passed since last update.

jestのテストでcss、scss、less絡みでSyntaxErrorが起きる場合の対処法

Posted at

問題

テスト対象の.jsx内などでimport "./abc.css"などとかがあるとエラーになってしまう。

 FAIL  app/javascript/packs/locator/tests/part_item.spec.jsx
  ● Test suite failed to run

    /.../animate.css/animate.min.css:1
    ({"Object.<anonymous>":function(....jest){@charset "UTF-8";
                                              ^
    SyntaxError: Invalid or unexpected token

対処法参考

Using with webpack

Handling Static Assets
Next, let's configure Jest to gracefully handle asset files such as stylesheets and images. Usually, these files aren't particularly useful in tests so we can safely mock them out. However, if you are using CSS Modules then it's better to mock a proxy for your className lookups.

平たく言えば、cssとか画像とかテストする必要ないからそう言うファイル拡張子は何にもしないって事にすれば良いじゃん、という感じ

1つの解決方法

Jest CSS Modules

これを使えば楽そうだったので、

package.json

  "jest": {
    //この行を追加 正規表現は適切なもに変更
    "moduleNameMapper": {
      "\\.(css|scss)$": "<rootDir>/node_modules/jest-css-modules"
    }
  },

これでテストを再起動させればエラーは出なくなる

23
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
13