📋

Karma + webpack + TypeScript 2017/2

2021/07/04に公開

今後思考停止して Karma + webpack + TypeScript を組むための覚え書き。

環境

node -v
v6.9.4

yarn --version
0.19.1

初期化とインストール

yarn init -y
yarn add --dev @types/jasmine jasmine-core jasmine-spec-reporter karma karma-chrome-launcher karma-cli karma-jasmine karma-webpack ts-loader typescript webpack
$(yarn bin)/tsc --init
$(yarn bin)/karma init

Which testing framework do you want to use ?
> jasmine

Do you want to use Require.js ?
> no

Do you want to capture any browsers automatically ?
> Chrome
>

What is the location of your source and test files ?
> ./test.js
>

Should any of the files included by the previous patterns be excluded ?
>

Do you want Karma to watch all the files and run the tests on change ?
> yes

Karma 設定に追記

// Karma configuration
module.exports = function(config) {
  config.set({

    // snip

    // list of files / patterns to load in the browser
    files: [
      './test.js'
    ],

    // snip

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      './test.js': ['webpack']
    },

    webpack: {
      resolve: {
        extensions: ['.ts', '.js']
      },
      module: {
        rules: [
          {test: /\.ts$/, use: [{loader: 'ts-loader'}]}
        ]
      }
    },

    // snip

  })
}

files./**/*.spec.tsとせず./test.jsでまとめるのがミソ。

test.js

const testsContext = require.context('./src', true, /\.spec\.ts$/)
testsContext.keys().forEach(testsContext)

テストファイル例

it('should...', () => {
  expect(1).toBe(2)
})

実行

$(yarn bin)/karma start

Chrome 56.0.2924 (Mac OS X 10.12.3)  should... FAILED
	Expected 1 to be 2.
	    at Object.<anonymous> (test.js:98:15)
Chrome 56.0.2924 (Mac OS X 10.12.3): Executed 1 of 1 (1 FAILED) ERROR (0.034 secs / 0.003 secs)

karma-typescript-preprocessor が個人的に合わなかったので、このやり方でいく。

Discussion