本文將探討如何搭建測試環(huán)境、以及Angular測試工具集。
測試環(huán)境
絕大部分都是利用Angular Cli來創(chuàng)建項(xiàng)目,因此,默認(rèn)已經(jīng)集成我們所需要的npm包與腳本;當(dāng)然,如果你是使用自建或官網(wǎng) quickstart 的話,需要自行安裝;但所有核心數(shù)據(jù)全都是一樣的。
Angular單元測試我們可以將其分成兩類:獨(dú)立單獨(dú)測試與Angular測試工具集。
Pipe與Service適為獨(dú)立單獨(dú)測試,因?yàn)樗鼈冎恍枰?new
實(shí)例類即可;同樣是無法與Angular組件進(jìn)行任何交互。
與之相反就是Angular測試工具集。
測試框架介紹
Jasmine
Jasmine測試框架提供了編寫測試腳本的工具集,而且非常優(yōu)秀的語義化,讓測試代碼看起來像是在讀一段話。
Karma
有測試腳本,還需要Karma來幫忙管理這些腳本,以便于在瀏覽器中運(yùn)行。
Npm 包
如果你非要折騰,那么最簡單的辦法便是通過Angular Cli創(chuàng)建一個新項(xiàng)目,然后將以下Npm包復(fù)制到您折騰的項(xiàng)目中。
"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 運(yùn)行器運(yùn)行起來,而對于 Jasmine,是在我們編寫測試腳本時才會使用到,因此,暫時無須過度關(guān)心。
我們需要在根目錄創(chuàng)建 karma.conf.js
文件,這相當(dāng)于一些約定。文件是為了告知karma需要啟用哪些插件、加載哪些測試腳本、需要哪些測試瀏覽器環(huán)境、測試報告通知方式、日志等等。
karma.conf.js
以下是Angular Cli默認(rèn)提供的 karma 配置文件:
// 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({
// 基礎(chǔ)路徑(適用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: {
// 當(dāng)測試運(yùn)行完成后是否清除上文
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
// 哪些文件需要被瀏覽器加載,后面會專門介紹 `test.ts`
files: [
{ pattern: './src/test.ts', watched: false }
],
// 允許文件到達(dá)瀏覽器之前進(jìn)行一些預(yù)處理操作
// 非常豐富的預(yù)處理器: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】的配置項(xiàng)
coverageIstanbulReporter: {
// 覆蓋率報告方式
reports: ['html', 'lcovonly'],
fixWebpackSourcePaths: true
},
// 指定angular cli環(huán)境
angularCli: {
environment: 'dev'
},
// 測試結(jié)果報告方式
reporters: config.angularCli && config.angularCli.codeCoverage ?
['progress', 'coverage-istanbul'] :
['progress', 'kjhtml'],
port: 9876,
colors: true,
// 日志等級
logLevel: config.LOG_INFO,
// 是否監(jiān)聽測試文件
autoWatch: true,
// 測試瀏覽器列表
browsers: ['Chrome'],
// 持續(xù)集成模式,true:表示瀏覽器執(zhí)行測試后退出
singleRun: false
});
};
以上配置基本上可以滿足我們的需求;一般需要變動的,我想是測試瀏覽器列表了,因?yàn)閗arma支持所有市面上的瀏覽器。另外,當(dāng)你使用 Travis CI 持續(xù)集成時,啟動一個禁用沙箱環(huán)境Chrome瀏覽器會讓我們少了很多事:
customLaunchers: {
Chrome_travis_ci: {
base: 'Chrome',
flags: ['--no-sandbox']
}
}
有關(guān)karma config文件的所有信息,請參與官網(wǎng)文檔。
test.ts
在編寫 karma.conf.js
時,我們配置過瀏覽器加載的文件指向的是 ./src/test.ts
文件。作用是為了引導(dǎo) karma 啟動,代碼也簡單許多:
// 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 試一下,哪怕無任何測試代碼,也是可以運(yùn)行的。
如果是Angular Cli那么 ng test
。折騰的用 node "./node_modules/karma-cli/bin/karma" start
最后,打開瀏覽器:http://localhost:9876
,可以查看測試報告。
簡單示例
既然環(huán)境搭好,那么我們來寫個簡單示例試一下。
創(chuàng)建 ./src/demo.spec.ts
文件。.spec.ts為后綴這是一個約定,遵守它。
describe('demo test', () => {
it('should be true', () => {
expect(true).toBe(true);
})
});
運(yùn)行 ng test
后,我們可以在控制臺看到:
Chrome 58.0.3029 (Windows 10 0.0.0): Executed 1 of 1 SUCCESS (0.031 secs / 0.002 secs)
或者瀏覽器:
1 spec, 0 failures
demo test
true is true
DEBUG
Karma 運(yùn)行后打開的頁面的右上角有一個【DEBUG】,會打開另一個頁面,此時,如果你打開 DevTools (chrome快捷鍵:Ctrl+Shift+I
),當(dāng)你重新刷新頁面后,遇到 debugger;
時會進(jìn)入斷點(diǎn)狀態(tài)。
不管怎么樣,畢竟我們已經(jīng)進(jìn)入Angular單元測試的世界了。
Angular測試工具集
普通類諸如Pipe或Service,只需要通過簡單的 new
創(chuàng)建實(shí)例。而對于指令、組件而言,需要一定的環(huán)境。這是因?yàn)锳ngular的模塊概念,要想組件能運(yùn)行,首先得有一個 @NgModule
定義。
工具集的信息量并不很多,你很容易可以掌握它。下面我簡略說明幾個最常用的:
TestBed
TestBed
就是Angular測試工具集提供的用于構(gòu)建一個 @NgModule
測試環(huán)境模塊。當(dāng)然有了模塊,還需要利用 TestBed.createComponent
創(chuàng)建一個用于測試目標(biāo)組件的測試組件。
異步
Angular到處都是異步,而異步測試可以利用工具集中 async
、fakeAsync
編寫優(yōu)雅測試代碼看著是同步。
工具集還有更多,這一切我們將在Angular單元測試-組件與指令單元測試逐一說明。
那么下一篇,我們將介紹如何使用Jasmine進(jìn)行Angular單元測試。
happy coding!