如何搭建测试环境?Angular测试工具集介绍


本文摘自PHP中文网,作者青灯夜游,侵删。

本文将探讨如何搭建测试环境、以及Angular测试工具集。

测试环境

绝大部分都是利用Angular Cli来创建项目,因此,默认已经集成我们所需要的npm包与脚本;当然,如果你是使用自建或官网 quickstart 的话,需要自行安装;但所有核心数据全都是一样的。【相关教程推荐:angular教程】

Angular单元测试我们可以将其分成两类:独立单独测试与Angular测试工具集。

Pipe与Service适为独立单独测试,因为它们只需要 new 实例类即可;同样是无法与Angular组件进行任何交互。

与之相反就是Angular测试工具集。

测试框架介绍

Jasmine

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

Karma

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

Npm 包

如果你非要折腾,那么最简单的办法便是通过Angular Cli创建一个新项目,然后将以下Npm包复制到您折腾的项目中。

1

2

3

4

5

6

7

8

"jasmine-core": "~2.5.2",

"jasmine-spec-reporter": "~3.2.0",

"karma": "~1.4.1",

"karma-chrome-launcher": "~2.1.1",

"karma-cli": "~1.0.1",

"karma-jasmine": "~1.1.0",

"karma-jasmine-html-reporter": "^0.2.2",

"karma-coverage-istanbul-reporter": "^0.2.0"

那么,我们重要还是看配置脚本部分。

配置脚本

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

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

karma.conf.js

以下是Angular Cli默认提供的 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

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

60

// 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。折腾的用 node "./node_modules/karma-cli/bin/karma" start

最后,打开浏览器: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 后,我们可以在控制台看到:

1

Chrome 58.0.3029 (Windows 10 0.0.0): Executed 1 of 1 SUCCESS (0.031 secs / 0.002 secs)

或者浏览器:

1

2

3

1 spec, 0 failures

demo test

  true is true

不管怎么样,毕竟我们已经进入Angular单元测试的世界了。

Angular测试工具集

普通类诸如Pipe或Service,只需要通过简单的 new 创建实例。而对于指令、组件而言,需要一定的环境。这是因为Angular的模块概念,要想组件能运行,首先得有一个 @NgModule 定义。

工具集的信息量并不很多,你很容易可以掌握它。下面我简略说明几个最常用的:

TestBed

TestBed 就是Angular测试工具集提供的用于构建一个 @NgModule 测试环境模块。当然有了模块,还需要利用 TestBed.createComponent 创建一个用于测试目标组件的测试组件。

异步

Angular到处都是异步,而异步测试可以利用工具集中 asyncfakeAsync 编写优雅测试代码看着是同步。

工具集还有更多,这一切我们将在[Angular单元测试-组件与指令单元测试]()逐一说明。

happy coding!

以上就是如何搭建测试环境?Angular测试工具集介绍的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

Angular入门学习之环境和项目的搭建

浅谈Angular10配置@路径别名的方法

浅谈Angular中elem.scope()、elem.isolatescope和$compile(elem)(scope)中scope的区别

Angular material的使用详解

浅谈Angular指令中的4种设计模式

一文快速了解Angular中的ngrx/store框架

浅谈Angular组件的交互方式

Angular cli是什么以及如何安装

浅谈Angular如何使用ng-content进行内容投影

如何安装和使用Angular cli?(图文详解)

更多相关阅读请进入《Angular》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...