Karma 5:集成 Karma 和 Angular2

时间:2023-01-01 06:18:59

集成 Karma 和 Angular2 我们需要做很多工作,由于需要使用 TypeScript 进行开发,首先需要正确配置 Typescript ,然后正确配置对 Angular2 的引用。还要创建 Karma 的入口文件,以便进行打包。

1. 安装工具

安装 Angular2.beta.7

karma3@1.0. C:\study\karmaStudy\karma3
├── angular2@2.0.-beta.
├── UNMET PEER DEPENDENCY es6-promise@^3.0.
├── UNMET PEER DEPENDENCY es6-shim@^0.33.
├── UNMET PEER DEPENDENCY reflect-metadata@0.1.
├── UNMET PEER DEPENDENCY rxjs@5.0.-beta.
└── UNMET PEER DEPENDENCY zone.js@0.5. npm WARN EPEERINVALID angular2@2.0.-beta. requires a peer of es6-promise@^3.0. but none was installed.
npm WARN EPEERINVALID angular2@2.0.-beta. requires a peer of es6-shim@^0.33. but none was installed.
npm WARN EPEERINVALID angular2@2.0.-beta. requires a peer of reflect-metadata@0.1. but none was installed.
npm WARN EPEERINVALID angular2@2.0.-beta. requires a peer of rxjs@5.0.-beta. but none was installed.
npm WARN EPEERINVALID angular2@2.0.-beta. requires a peer of zone.js@0.5. but none was installed.

如果使用了 NPM 3 以上版本,需要手工安装依赖库

es6-promise@^3.0.2
es6-shim@^0.33.3
reflect-metadata@0.1.2
rxjs@5.0.0-beta.2
zone.js@0.5.15

安装 webpack 和它的插件 ts-loader

npm i -D webpack ts-loader

安装 karma 及其插件

npm i -D karma karma-chrome-launcher karma-jasmine jasmine-core karma-webpack

安装 typings

这里,我们需要 es6-shim 的定义和 jasmine 的定义。

奇怪的是 install 必须是第一个参数。

安装 jasmine 的定义

> typings install --save --ambient jasmine
? Found jasmine typings for DefinitelyTyped. Continue? Yes
Installing jasmine@~2.2.0 (DefinitelyTyped)... jasmine
└── (No dependencies)

安装 es6-shim 的定义

> typings install --save --ambient es6-shim
? Found es6-shim typings for DefinitelyTyped. Continue? Yes
Installing es6-shim@~0.31. (DefinitelyTyped)... es6-shim
└── (No dependencies)

这些组件安装完成之后,你的 package.json 应该是这样的。

{
"name": "karma3",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"angular2": "^2.0.0-beta.7",
"es6-promise": "^3.0.2",
"es6-shim": "^0.33.3",
"reflect-metadata": "^0.1.2",
"rxjs": "^5.0.0-beta.2",
"zone.js": "^0.5.15"
},
"devDependencies": {
"jasmine-core": "^2.4.1",
"karma": "^0.13.21",
"karma-chrome-launcher": "^0.2.2",
"karma-jasmine": "^0.3.7",
"karma-webpack": "^1.7.0",
"ts-loader": "^0.8.1",
"typings": "^0.6.8",
"webpack": "^1.12.14"
}
}

2. 编写示例代码

在项目目录中创建 src 文件夹,在其中创建名为 MyMaths.ts 的代码文件

import { Component } from 'angular2/core';
import { Injectable } from 'angular2/core'; @Component({
selector: "hello"
})
export class MyMaths{
add(a: number, b:number ){
return a + b;
}
}

在项目目录中,创建 test 和其中的 unit 子文件夹,我们的单元测试将会保存在这个文件夹中。

创建名为 MyMaths.spec.ts 的单元测试文件

import { MyMaths } from '../../src/MyMaths';

describe('hello, unit test.', function(){
var myMaths = new MyMaths(); it('hello, add', function(){
let a = 2, b = 3;
let result = myMaths.add(a, b );
expect(result).toBe( 5 );
}); it('it should failded.', function(){
let a = 2, b = 3;
let result = myMaths.add(a, b);
expect(result).toBe( 100 );
})
});

3. 配置环境

1. 配置 TypeScript

在项目目录中创建名为 tsconfig.Json 的 TypeScript配置文件。

注意其中的 noEmitHelpers 必须配置为 false,emitDecoratorMetadata 必须配置为 true.

{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"noEmitHelpers": false,
"noImplicitAny": false,
"sourceMap": true
}, "exclude":[
"node_modules",
"typings/main",
"typings/main.d.ts"
], "filesGlob": [
"./src/**/*.ts",
"!./node_modules/**/*.ts"
]
}

2. 配置 webpack

webpack 的默认配置文件为 webpack.config.js,我们这里用来测试打包的正确性。

var path = require('path');

var ROOT_PATH = path.resolve(__dirname);
var BUILD_PATH = path.resolve(ROOT_PATH, 'build'); module.exports = {
resolve: {
extensions: ['', '.js', '.ts']
},
entry: "./spec-bundle.js", output: {
path: BUILD_PATH,
filename: 'bundle.js'
}, module: {
loaders: [
{ test: /\.ts$/, loader: 'ts-loader' }
]
}, node: {
global: 'window',
progress: false,
crypto: 'empty',
module: false,
clearImmediate: false,
setImmediate: false
}
};

3. 配置 karma

首先,创建 karma 的入口文件,我们通过这个文件将所有的测试代码和待测试代码一起打包。

创建名为 spec-bundle.js 的入口文件。

require('es6-shim');
require('es6-promise');
require('reflect-metadata');
require('rxjs');
require('zone.js'); var testContext = require.context('./test', true, /\.spec\.ts/);
var appContext = require.context('./src', true, /\.ts/); appContext.keys().forEach(appContext);
testContext.keys().forEach(testContext); var domAdapter = require('angular2/src/platform/browser/browser_adapter');
domAdapter.BrowserDomAdapter.makeCurrent();

然后,创建 karma 的配置文件。可以先使用 karma init 创建基本的配置信息,然后修改为我们需要的内容。

// Karma configuration
// Generated on Thu Feb 25 2016 10:11:36 GMT+0800 (China Standard Time) module.exports = function(config) {
var testWebpackConfig = require('./webpack.test.config.js'); config.set({ // base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '', // frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'], // list of files / patterns to load in the browser
files: [
'spec-bundle.js'
], // list of files to exclude
exclude: [
], // preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'spec-bundle.js': ['webpack']
},
webpack: testWebpackConfig, // test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'], // web server port
port: 9876, // enable / disable colors in the output (reporters and logs)
colors: true, // level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes
autoWatch: true, // start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'], // Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true, // Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
}

这里用到了 webpack 进行打包,而且声明了使用 webpack.test.config.js 作为 webpack 的配置文件。

创建这个名为 webpack.test.config.js 的配置文件。这个文件不需要入口文件,也不需要输出目录。Karma 将提供入口和获取打包之后的输出。

var path = require('path');

var ROOT_PATH = path.resolve(__dirname);
var BUILD_PATH = path.resolve(ROOT_PATH, 'build'); module.exports = {
resolve: {
extensions: ['', '.js', '.ts']
}, module: {
loaders: [
{ test: /\.ts$/, loader: 'ts-loader' }
]
}, node: {
global: 'window',
progress: false,
crypto: 'empty',
module: false,
clearImmediate: false,
setImmediate: false
}
};

4. 测试

1. 检查打包是否正确。

由于已经配置了 webpack,可以直接在项目目录中执行 webpack,应该可以在 build 子目录中看到打包之后的文件,文件中应该已经正确包含了我们的所有代码。

2. 执行测试

执行 karma start ,可以完成测试过程。

   ::15.560:INFO [karma]: Karma v0.13.21 server started at http://localhost:9876/
::15.576:INFO [launcher]: Starting browser Chrome
::18.349:INFO [Chrome 47.0. (Windows 0.0.)]: Connected on socket /#uBbzQ9xOIQzT1jNOAAAA with id
Chrome 47.0. (Windows 0.0.) hello, unit test. it should failded. FAILED
Expected to be .
at Object.<anonymous> (C:/study/karmaStudy/karma3/spec-bundle.js::)
Chrome 47.0. (Windows 0.0.): Executed of ( FAILED) (0.026 secs / 0.013 secs)

5. 讨论

这个过程的配置信息较为复杂,需要耐心检查错误。