Angular单元测试与集成测试
使用Angular CLI创建的App已配置好测试环境,生成了测试配置文件和样例代码。默认,Angular单元测试使用Jasmine测试框架和Karma测试运行器,集成测试使用Jasmine测试框架和Protractor end-to-end 测试框架。
单元测试Jasmine是一个用于测试JavaScript的行为驱动开发框架,不依赖于任何其他JavaScript框架。 配置文件单元测试配置文件test.ts和karma.conf.js: 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。 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。 浏览器配置Karma支持的浏览器:
可同时配置多个浏览器进行测试,要启用其他浏览器,需安装依赖,比如启用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 在控制台会输出测试结果,还会打开浏览器: 浏览器会显示测试结果,总测试数,失败数。在顶部,每个点或叉对应一个测试用例,点表示成功,叉表示失败,鼠标移到点或叉上会显示测试信息。点击测试结果中的某一行,可重新运行某个或某组(测试套件)测试。 常用参数: 自定义Launcherkarma-chrome-launcher、karma-firefox-launcher、karma-ie-launcher等均支持自定义Launcher,customLaunchers与--browsers结合使用可满足多种环境的测试需求。每种浏览器支持的自定义属性请查看Karma Browsers文档。 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/*"] } } 设定测试覆盖率指标 coverageIstanbulReporter: { reports: [ ‘html‘,‘lcovonly‘ ],fixWebpackSourcePaths: true,thresholds: { statements: 80,lines: 80,branches: 80,functions: 80 } } 测试报告中达到标准的背景为绿色。 LCOV coverageIstanbulReporter中reports参数为[ ‘html‘,‘lcovonly‘ ],会生成html和lcov两种格式的报告。报告文件lcov.info可与Sonar集成,在Sonar管理界面配置LCOV Files路径,即可在Sonar中查看测试情况。 编写测试待续... 集成测试集成测试使用Jasmine和Protractor测试框架,Protractor是Angular端到端测试框架。 安装Protractornpm install -g protractor 在项目中执行npm install时会安装protractor,不必单独执行以上命令。安装protractor后会安装两个命令行工具protractor和webdriver-manager(位于node_modulesprotractorbin目录),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_modulesprotractornode_moduleswebdriver-managerselenium目录下。 version get the current version 配置文件使用CLI创建的App会生成一个e2e项目,其中包含测试配置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等浏览器。 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‘] } }, 更多选项请查看相应驱动ChromeDriver、GeckoDriver。 Selenium Server配置使用Standalone Selenium Server时,需安装JDK。 webdriver-manager update webdriver-manager start 删除原配置中的directConnect、baseUrl: directConnect: true, 增加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模式: 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=e2eprotractor-ci.conf.js 编写测试待续... 参考资料Jasmine Behavior-Driven JavaScript (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |