Angular を利用したプロジェクトで、ng test
コマンドで Karma + Jasmine でユニットテストを行った際にハマったことの備忘録です。
本記事では、Angular のテストツールは Karma + Jasmineを想定しています。
問題
ng test
を実行して、下記のようなエラーが出た場合を想定します。
ERROR in ./src/app/app.component.scss
Module build failed (from ./node_modules/sass-loader/lib/loader.js):
@import 'theme';
^
File to import not found or unreadable: theme.
in /Users/xxxx/project/src/app/app.component.scss (line 1, column 1)
@ ./src/app/app.component.ts 16:21-52
@ ./src/app/app.component.spec.ts
@ ./src sync \.spec\.ts$
@ ./src/test.ts
該当の scss ファイルは例として、下記のようなものを想定します。
@import 'theme';
h1 {
color: $main;
}
インポート先のテーマ用 scss ファイルは下記とします。
$main: red;
app.component.scss の@import 'theme';
のようにルート相対パスで記述するために、 angular.json のarchitect.build.options
にstylePreprocessorOptions.includePaths
に任意のパスを追加しています。
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"stylePreprocessorOptions": {
"includePaths": [
"src/theme/default"
]
},
...
解決方法
architect.build.options
と同様にarchitect.test.options
にstylePreprocessorOptions.includePaths
を設定します。
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"stylePreprocessorOptions": {
"includePaths":
"src/theme/default"
]
},
...
上記の記述を追加すると、ng test
を実行すると、 Karma が動作するようになります。
参考