测试框架简介

Jasmine

Jasmine测试框架提供了编写测试脚本的工具集,而且非常优秀的语义化,让测试代码看起来像是在读一段话。

Karma

有测试脚本,还需要Karma来帮忙管理这些脚本,以便于在浏览器中运行。

配置脚本

我们核心是需要让 karma 运行器运行起来,而对于 Jasmine,是在我们编写测试脚本时才会使用到,因此,暂时无须过度关心。

我们需要在根目录创建 karma.conf.js 文件,这相当于一些约定。文件是为了告知karma需要启用哪些插件、加载哪些测试脚本、需要哪些测试浏览器环境、测试报告通知方式、日志等等。 通过angular cli 创建一个项目时默认即创建了karma.conf.js

karma.conf.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Karma configuration file, see link for more information
// https://karma-runner.github.io/0.13/config/configuration-file.html
module.exports = function(config) {
    config.set({
        // 基础路径(适用file、exclude属性)
        basePath: '',
        // 测试框架,@angular/cli 指Angular测试工具集
        frameworks: ['jasmine', '@angular/cli'],
        // 加载插件清单
        plugins: [
            require('karma-jasmine'),
            require('karma-chrome-launcher'),
            require('karma-jasmine-html-reporter'),
            require('karma-coverage-istanbul-reporter'),
            require('@angular/cli/plugins/karma')
        ],
        client: {
            // 当测试运行完成后是否清除上文
            clearContext: false // leave Jasmine Spec Runner output visible in browser
        },
        // 哪些文件需要被浏览器加载,后面会专门介绍  `test.ts`
        files: [
            { pattern: './src/test.ts', watched: false }
        ],
        // 允许文件到达浏览器之前进行一些预处理操作
        // 非常丰富的预处理器:https://www.npmjs.com/browse/keyword/karma-preprocessor
        preprocessors: {
            './src/test.ts': ['@angular/cli']
        },
        // 指定请求文件MIME类型
        mime: {
            'text/x-typescript': ['ts', 'tsx']
        },
        // 插件【karma-coverage-istanbul-reporter】的配置项
        coverageIstanbulReporter: {
            // 覆盖率报告方式
            reports: ['html', 'lcovonly'],
            fixWebpackSourcePaths: true
        },
        // 指定angular cli环境
        angularCli: {
            environment: 'dev'
        },
        // 测试结果报告方式
        reporters: config.angularCli && config.angularCli.codeCoverage ?
            ['progress', 'coverage-istanbul'] :
            ['progress', 'kjhtml'],
        port: 9876,
        colors: true,
        // 日志等级
        logLevel: config.LOG_INFO,
        // 是否监听测试文件
        autoWatch: true,
        // 测试浏览器列表
        browsers: ['Chrome'],
        // 持续集成模式,true:表示浏览器执行测试后退出
        singleRun: false
    });
};

以上配置基本上可以满足我们的需求;一般需要变动的,我想是测试浏览器列表了,因为karma支持所有市面上的浏览器。另外,当你使用 Travis CI 持续集成时,启动一个禁用沙箱环境Chrome浏览器会让我们少了很多事:

1
2
3
4
5
6
        customLaunchers: {
            Chrome_travis_ci: {
                base: 'Chrome',
                flags: ['--no-sandbox']
            }
        }

有关karma config文件的所有信息,请参与官网文档。

test.ts

在编写 karma.conf.js 时,我们配置过浏览器加载的文件指向的是 ./src/test.ts 文件。作用是为了引导 karma 启动,代码也简单许多:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// This file is required by karma.conf.js and loads recursively all the .spec and framework files

import 'zone.js/dist/long-stack-trace-zone';
import 'zone.js/dist/proxy.js';
import 'zone.js/dist/sync-test';
import 'zone.js/dist/jasmine-patch';
import 'zone.js/dist/async-test';
import 'zone.js/dist/fake-async-test';
import { getTestBed } from '@angular/core/testing';
import {
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';

// Unfortunately there's no typing for the `__karma__` variable. Just declare it as any.
declare var __karma__: any;
declare var require: any;

// Prevent Karma from running prematurely.
__karma__.loaded = function () {};

// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting()
);
// Then we find all the tests.
// 所有.spec.ts文件
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);
// Finally, start Karma to run the tests.
__karma__.start();

一切就绪后,我们可以尝试启动 karma 试一下,哪怕无任何测试代码,也是可以运行的。

如果是Angular Cli那么直接执行 ng test

最后,打开浏览器:http://localhost:9876 ,可以查看测试报告。

简单示例

既然环境搭好,那么我们来写个简单示例试一下。

创建 ./src/demo.spec.ts 文件。.spec.ts为后缀这是一个约定,遵守它。

1
2
3
4
5
describe('demo test', () => {
    it('should be true', () => {
        expect(true).toBe(true);
    })
});

运行 ng test 后,我们可以在控制台看到:

Chrome 58.0.3029 (Windows 10 0.0.0): Executed 1 of 1 SUCCESS (0.031 secs / 0.002 secs) 或者浏览器:

1
2
3
4
1 spec, 0 failures
demo test
  true is true
DEBUG

Karma 运行后打开的页面的右上角有一个【DEBUG】,会打开另一个页面,此时,如果你打开 DevTools (chrome快捷键:Ctrl+Shift+I),当你重新刷新页面后,遇到 debugger; 时会进入断点状态。