【发布时间】:2016-01-28 00:15:19
【问题描述】:
我一直在尝试使用 Karma+Jasmine 来运行用 TypeScript 编写的测试。
在网上搜索,似乎有不少人做到了这样的壮举,但我找不到关于如何做到这一点的完整指南。环境:
- 使用 ES6 模块的打字稿
- 业力
- 茉莉花
- 咕噜声
如何设置整件事?
【问题讨论】:
标签: gruntjs typescript jasmine karma-runner karma-jasmine
我一直在尝试使用 Karma+Jasmine 来运行用 TypeScript 编写的测试。
在网上搜索,似乎有不少人做到了这样的壮举,但我找不到关于如何做到这一点的完整指南。环境:
如何设置整件事?
【问题讨论】:
标签: gruntjs typescript jasmine karma-runner karma-jasmine
查看GitHub repository 获取完整源代码。
让我们从devDependencies开始:
"devDependencies": {
"grunt": "^0.4.5",
"grunt-contrib-watch": "^0.6.1",
"grunt-karma": "^0.12.1",
"grunt-ts": "^5.1.0",
"jasmine-core": "^2.3.4",
"karma": "^0.13.15",
"karma-jasmine": "^0.3.6",
"karma-phantomjs-launcher": "^0.2.1",
"karma-requirejs": "^0.2.3",
"load-grunt-tasks": "^3.3.0",
"phantomjs": "^1.9.18",
"requirejs": "^2.1.22"
}
我们查看所有.ts 文件,并在更改后首先转换它们,然后运行测试:
watch: {
typescript: {
// Watching all typescript files (specs and units)
files: [ 'source/**/*.ts' ],
// First transpile, then run tests
tasks: [ 'ts:default', 'karma:continuous:run' ],
options: {
spawn: false
}
}
},
我们使用 amd 模块转译所有 .ts 文件。请注意,我们需要 jasmine 的类型:
ts: {
default: {
src: [
// Note that we add the typings for jasmine here
'typings/jasmine.d.ts',
// We compile all .ts files (specs and units)
'source/**/*.ts'
],
options: {
// We need to convert ES6 to ES5 and use amd so it works
// with RequireJS
module: 'amd',
fast: 'never'
},
// We output all files to a temp folder
outDir: 'transpiled'
}
},
所有.ts 文件都在transpiled 文件夹中,我们可以运行业力测试:
karma: {
options: {
configFile: 'karma.conf.js'
},
continuous: {
logLevel: 'INFO',
singleRun: false,
}
}
最棘手的部分:
requirejs 添加为框架。include 标志设置为 false。test-main.js 的文件然后扫描这些文件并动态加载所有.spec 文件进行测试。 test-main.js 由 Karma 生成,请参阅 this guide 了解更多信息。像这样:
module.exports = function(config) {
config.set({
// Note that we also use `requirejs`
frameworks: [ 'jasmine', 'requirejs' ],
files: [
// We add all transpiled files (specs and unit) with included set
// to false.
{ pattern: 'transpiled/**/*.js', included: false },
// Test main will search the files for specs and load them
// dynamically.
'test-main.js'
],
reporters: [ 'progress' ],
browsers: [ 'PhantomJS' ],
autoWatch: false,
singleRun: true
})
}
【讨论】:
看看使用karma-typescript-preprocessor 可能比观看、编译然后运行测试要容易一些。
这可以很容易地设置到您的 karma 和/或 grunt 配置中。
【讨论】: