我将尝试解释如何在Webpack和Typescript源代码中使用Karma测试运行器。以下是一个示例测试文件:
test.spec.ts
以下是相关的karma配置: karma.config.js
在运行
然而,手动使用上述配置运行webpack时,它将输出一个正确的javascript文件,因此配置似乎是正确的...
为了完整起见,这些是
var message: string = 'yay';
alert(message);
describe('1st tests', () => {
it('true is true', () => expect(true).toBe(true));
});
以下是相关的karma配置: karma.config.js
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-webpack'),
require('karma-jasmine-html-reporter')
],
client: {
builtPaths: ['app/'], // add more spec base paths as needed
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
customLaunchers: {
// From the CLI. Not used here but interesting
// chrome setup for travis CI using chromium
Chrome_travis_ci: {
base: 'Chrome',
flags: ['--no-sandbox']
}
},
files: [
{ pattern: 'app/test.spec.ts', included: true, watched: true },
],
exclude: [],
preprocessors: {
// add webpack as preprocessor
'app/test.spec.ts': ['webpack']
},
webpack: {
// karma watches the test entry points
// (you don't need to specify the entry option)
// webpack watches dependencies
// webpack configuration
resolve: {
//root: [ path.join(__dirname, 'app') ],
extensions: ['', '.ts', '.js']
},
module: {
loaders: [
// .ts files for TypeScript
{ test: /\.ts$/, loaders: ['awesome-typescript-loader', 'angular2-template-loader'], exclude: '/node_modules/' },
]
}
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
})
}
在运行
karma start
时,没有发现任何测试。浏览器会启动,但它会显示找到0个测试。当我将.ts
扩展名更改为.js
并更新karma配置文件后,它可以工作,因此很明显是Typescript引起的问题。然而,手动使用上述配置运行webpack时,它将输出一个正确的javascript文件,因此配置似乎是正确的...
为了完整起见,这些是
package.json
和tsconfig.json
文件:
package.json
{
"name": "karma-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"karma": "karma init"
},
"author": "",
"license": "ISC",
"private": true,
"devDependencies": {
"@types/jasmine": "^2.5.41",
"angular2-template-loader": "^0.6.0",
"awesome-typescript-loader": "^3.0.0-beta.18",
"jasmine-core": "^2.5.2",
"karma": "^1.4.0",
"karma-chrome-launcher": "^2.0.0",
"karma-jasmine": "^1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"karma-webpack": "^2.0.1",
"typescript": "^2.1.5",
"webpack": "^1.14.0"
}
}
tsconfig.json
{
"compileOnSave": false,
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true
},
"awesomeTypescriptLoaderOptions": {
"useWebpackText": true
},
"exclude": [
"node_modules"
]
}