ユニットテスト(Karma)もTypeScriptで: karma-webpack編

以前の記事
ユニットテスト(Karma)もTypeScriptで - ryotah’s blog

これだと、モジュールのimportができないねえ。

というわけでkarma-webpackを試そうと思います。
GitHub - webpack-contrib/karma-webpack: Use webpack with karma.

テスト環境は Karma Chrome Jasmine。

// karma.conf.js

var webpackConfig = require('./webpack.config');
module.exports = function(config) {
  config.set({
    mime: {
      'text/x-typescript': ['ts','tsx']
    },
    basePath: '',
    frameworks: ['jasmine'],
    patterns to load in the browser
    files: [
      'test/**/*.spec.ts'
    ],
    exclude: [
    ],
    preprocessors: {
      'test/**/*.spec.ts': ['webpack'],
    },
    webpack: {
      module: webpackConfig.module,
      resolve: webpackConfig.resolve
    },
    reporters: ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false,
    concurrency: Infinity
  })
}

基本的にはkarm initでkarma.conf.jsを生成した後、 preprocessorswebpackの部分を追加するだけでおk。

これに加えて、Chromeでテストが実行されなかったので mime: {'text/x-typescript': ['ts','tsx']} の設定も追加しています。

ng test ends with "Executed 0 of 0 ERROR" · Issue #2838 · angular/angular-cli · GitHub


他のファイルも参考程度に。

.
├── karma.conf.js
├── node_modules
├── package.json
├── src
├── test
├── tsconfig.json
└── webpack.config.js
// package.json

{
  "name": "webpack2-karm",

  // (省略)

  "devDependencies": {
    "@types/jasmine": "^2.5.43",
    "jasmine-core": "^2.5.2",
    "karma": "^1.5.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-jasmine": "^1.1.0",
    "karma-webpack": "^2.0.2",
    "ts-loader": "^2.0.1",
    "typescript": "^2.2.1",
    "webpack": "^2.2.1"
  }
}
// tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs"
  },
  "exclude": [
    "node_modules"
  ]
}
// webpack.config.js

var path = require('path');

module.exports = {
  entry: './src/foo',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'foo.bundle.js'
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js']
  },
  module: {
    rules: [
      { test: /\.tsx?$/, use: 'ts-loader' }
    ]
  }
}