Angular单元测试与集成测试

使用Angular CLI创建的App已配置好测试环境,生成了测试配置文件和样例代码。默认,Angular单元测试使用Jasmine测试框架和Karma测试运行器,集成测试使用Jasmine测试框架和Protractor end-to-end 测试框架。

单元测试

Jasmine是一个用于测试JavaScript的行为驱动开发框架,不依赖于任何其他JavaScript框架。
Karma是测试运行器,为开发人员提供了高效的、真实的测试环境,支持多种浏览器,易于调试。

配置文件

单元测试配置文件test.ts和karma.conf.js:
test.ts

import 'zone.js/dist/zone-testing';
import { getTestBed } from '@angular/core/testing';
import {
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';

declare const require: any;

// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting()
);
// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);

测试文件扩展名必须为.spec.ts。
karma.conf.js

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
    client: {
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, '../coverage'),
      reports: ['html', 'lcovonly'],
      fixWebpackSourcePaths: true
    },
    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });
};

默认使用Chrome浏览器,可生成单元测试报告和覆盖率报告,覆盖率报告保存在根目录coverage文件夹内,启用autoWatch。
singleRun默认为false,如设为true则测试结束后会自动退出并根据测试结果返回代码0或1,常用于CI环境。

浏览器配置

Karma支持的浏览器:

  • Chrome
  • ChromeCanary
  • ChromeHeadless
  • PhantomJS
  • Firefox
  • Opera
  • IE
  • Safari

可同时配置多个浏览器进行测试,要启用其他浏览器,需安装依赖,比如启用Firefox:

npm install karma-firefox-launcher --save-dev

然后在karma.conf.js内增加配置:

...
require('karma-chrome-launcher'),
require('karma-firefox-launcher'),
...
browsers: ['Chrome', 'Firefox'],
...

运行测试

使用CLI创建App生成了一个单元测试文件app.component.spec.ts。运行CLI命令 ng test 即可执行单元测试:

ng test

在控制台会输出测试结果,还会打开浏览器:
Angular单元测试与集成测试
浏览器会显示测试结果,总测试数,失败数。在顶部,每个点或叉对应一个测试用例,点表示成功,叉表示失败,鼠标移到点或叉上会显示测试信息。点击测试结果中的某一行,可重新运行某个或某组(测试套件)测试。

常用参数:
--browsers 指定使用的浏览器
--code-coverage 输出覆盖率报告
--code-coverage-exclude 排除文件或路径
--karma-config 指定Karma配置文件
--prod 启用production环境
--progress 默认为true,在构建时将进度输出到控制台
--watch 默认为true,代码修改后会重新运行测试

自定义Launcher

karma-chrome-launcher、karma-firefox-launcher、karma-ie-launcher等均支持自定义Launcher,customLaunchers与--browsers结合使用可满足多种环境的测试需求。每种浏览器支持的自定义属性请查看Karma Browsers文档。
比如,CI环境下常用Headless模式,不必使用浏览器界面,karma.conf.js增加如下配置:

browsers: ['Chrome'],
customLaunchers: {
  ChromeHeadlessCI: {
    base: 'ChromeHeadless',
    flags: ['--no-sandbox']
  }
},

运行如下命令进行测试:

ng test --watch=false --progress=false --browsers=ChromeHeadlessCI

测试覆盖率

运行如下命令生成测试覆盖率报告,报告保存在项目根目录下的coverage文件夹内:

ng test --watch=false --code-coverage

如想每次测试都生成报告,可修改CLI配置文件angular.json:

"test": {
  "options": {
    "codeCoverage": true
  }
}

设置排除的文件或路径

ng test --watch=false --code-coverage --code-coverage-exclude=src/app/heroes/heroes.component.ts --code-coverage-exclude=src/app/hero-search/*

同样可以在angular.json中配置:

"test": {
  "options": {
    "codeCoverage": true,
    "codeCoverageExclude": ["src/app/heroes/heroes.component.ts", "src/app/hero-search/*"]
  }
}

设定测试覆盖率指标
编辑配置文件karma.conf.js,增加如下内容:

coverageIstanbulReporter: {
  reports: [ 'html', 'lcovonly' ],
  fixWebpackSourcePaths: true,
  thresholds: {
    statements: 80,
    lines: 80,
    branches: 80,
    functions: 80
  }
}

测试报告中达到标准的背景为绿色。
Angular单元测试与集成测试
LCOV
coverageIstanbulReporter中reports参数为[ 'html', 'lcovonly' ],会生成html和lcov两种格式的报告。报告文件lcov.info可与Sonar集成,在Sonar管理界面配置LCOV Files路径,即可在Sonar中查看测试情况。
Angular单元测试与集成测试

编写测试

待续...

集成测试

集成测试使用Jasmine和Protractor测试框架,Protractor是Angular端到端测试框架。

安装Protractor

npm install -g protractor

在项目中执行npm install时会安装protractor,不必单独执行以上命令。安装protractor后会安装两个命令行工具protractor和webdriver-manager(位于node_modules\protractor\bin目录),webdriver-manager负责管理驱动、启停Selenium Server。

webdriver-manager命令:

clean      removes all downloaded driver files from the out_dir
start      start up the selenium server
shutdown   shut down the selenium server
status     list the current available drivers
update     install or update selected binaries,更新的驱动保存在node_modules\protractor\node_modules\webdriver-manager\selenium目录下。
version    get the current version

配置文件

使用CLI创建的App会生成一个e2e项目,其中包含测试配置protractor.conf.js及测试代码。
protractor.conf.js

const { SpecReporter } = require('jasmine-spec-reporter');

exports.config = {
  allScriptsTimeout: 11000,
  specs: [
    './src/**/*.e2e-spec.ts'
  ],
  capabilities: {
    'browserName': 'chrome'
  },
  directConnect: true,
  baseUrl: 'http://localhost:4200/',
  framework: 'jasmine',
  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 30000,
    print: function() {}
  },
  onPrepare() {
    require('ts-node').register({
      project: require('path').join(__dirname, './tsconfig.e2e.json')
    });
    jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
  }
};

默认,Protractor使用Jasmine测试框架,使用直连方式连接Chrome浏览器,测试文件扩展名为.e2e-spec.ts。

浏览器配置

Protractor支持Chrome、Firefox、Safari、IE等浏览器。
多浏览器
Protractor可同时启动多个浏览器,用一个浏览器时,在配置中使用capabilities选项;用多个浏览器时,使用multiCapabilities:

multiCapabilities: [{
  browserName: 'firefox'
}, {
  browserName: 'chrome'
}]

另外需在package.json中增加配置:

"scripts": {
  "webdriver-update": "webdriver-manager update"
}

在运行测试前执行:

npm run webdriver-update

否则项目中的驱动不会更新(默认只有chrome驱动,在命令行运行webdriver-manager update仅更新全局的驱动),运行测试会报如下错误:

No update-config.json found. Run 'webdriver-manager update' to download binaries

浏览器选项

capabilities: {
  'browserName': 'chrome',
  'chromeOptions': {
    'args': ['show-fps-counter=true']
  }
},
capabilities: {
  'browserName': 'firefox',
  'moz:firefoxOptions': {
    'args': ['--safe-mode']
  }
},

更多选项请查看相应驱动ChromeDriverGeckoDriver

Selenium Server配置

使用Standalone Selenium Server时,需安装JDK。
更新driver后启动Selenium Server:

webdriver-manager update
webdriver-manager start

删除原配置中的directConnect、baseUrl:

directConnect: true,
baseUrl: 'http://localhost:4200/',

增加seleniumAddress(默认为http://localhost:4444/wd/hub):

seleniumAddress: 'http://localhost:4444/wd/hub',

运行测试

执行CLI命令 ng e2e即可运行集成测试:

ng e2e

常用参数:

--base-url  Base URL for protractor to connect to.
--configuration (-c)  A named configuration environment, as specified in the "configurations" section of angular.json.
--host  Host to listen on.
--port  The port to use to serve the application.
--prod  When true, sets the build configuration to the production environment.
--protractor-config  The name of the Protractor configuration file.
--webdriver-update  Try to update webdriver.

指定配置文件

不同的环境若配置不同,可使用不同的配置文件。

比如,在CI环境中启用Chrome Headless模式:
在e2e根目录下创建一名为protractor-ci.conf.js的新文件,内容如下:

const config = require('./protractor.conf').config;

config.capabilities = {
  browserName: 'chrome',
  chromeOptions: {
    args: ['--headless', '--no-sandbox']
  }
};

exports.config = config;

注意: windows系统要增加参数--disable-gpu

运行以下命令测试:

ng e2e --protractor-config=e2e\protractor-ci.conf.js

编写测试

待续...

参考资料

Jasmine Behavior-Driven JavaScript
Karma
Protractor - end-to-end testing for Angular

猜你喜欢

转载自blog.51cto.com/7308310/2319497