Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

問題

テスト対象の.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"
    }
  },

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away