LoginSignup
13
12

More than 5 years have passed since last update.

cssも画像もimportしてるjsファイルのテストを書く

Last updated at Posted at 2016-09-15

注意点2つほど

babel通さないとimportでコケる

mocha ./spec/**/*.js --compilers js:babel-core/register
  • import使ってる場合全般の話ですね
  • mochaなどはnode.js環境で実行される
  • 最新のv6でもes6 modulesはサポートしてないので、commonjsにトランスパイルする必要がある
  • --compilers js:babel-core/registerをセットすればok

画像やcssの読み込み箇所でエラーになる

なんでもimport...from ( require ) できて便利だが、mochaとかでテスト書くとこける

import style from './style.css'
import btn from '../../images/btn-back.svg'
  • mocha(node.js環境)では読み込まれてるファイルを.jsとしてパースしようとする
  • そして、パースエラー

対策1:require.extensions を使う

require() されたファイルの種類をチェックして、パースをスキップ

./test/setup.js
require.extensions['.css'] = () => null
require.extensions['.png'] = () => null
  • require.extensions はdeprecated(だが、削除しない予定らしい)

In the past, this list has been used to load non-JavaScript modules into Node.js by compiling them on-demand. However, in practice, there are much better ways to do this, such as loading modules via some other Node.js program, or compiling them to JavaScript ahead of time.

対策2: require hook を使う

  • babel-core/registercoffee/register で使われてるテクニック
  • 自力で実装しなくても、npm pkgを使って済ませれる
    • cssはcss-modules-require-hook
    • 画像はimages-require-hook
./test/setup.js
import 'css-modules-require-hook/preset'
import imgHook from 'images-require-hook'
imgHook(['.png', '.svg'], '../src/images')

このファイルを---require オプションで指定

mocha ./spec/**/*.js --compilers js:babel-core/register --require ./test/setup.js
13
12
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
13
12