《瀏覽器端測試:mocha往枷,chai框产,phantomjs》
目標(biāo)
建立一個 lesson7 項目,在其中編寫代碼错洁,我們暫時命名為 vendor
根據(jù)下面的步驟秉宿,最終的項目結(jié)構(gòu)應(yīng)該長這樣
這次我們測試的對象是上文提到的 fibonacci 函數(shù)
此函數(shù)的定義為 int fibonacci(int n)
- 當(dāng) n === 0 時,返回 0屯碴;n === 1時描睦,返回 1;
- n > 1 時,返回
fibonacci(n) === fibonacci(n-1) + fibonacci(n-2)
导而,如fibonacci(10) === 55
;
知識點
- 學(xué)習(xí)使用測試框架 mocha 進行前端測試 : http://mochajs.org/
- 了解全棧的斷言庫 chai: http://chaijs.com/
- 了解 headless 瀏覽器 phantomjs: http://phantomjs.org/
前端腳本單元測試
lesson6 的內(nèi)容都是針對后端環(huán)境中 node 的一些單元測試方案忱叭,出于應(yīng)用健壯性的考量,針對前端 js 腳本的單元測試也非常重要今艺。而前后端通吃韵丑,也是 mocha 的一大特點。
首先虚缎,前端腳本的單元測試主要有兩個困難需要解決埂息。
運行環(huán)境應(yīng)當(dāng)在瀏覽器中,可以操縱瀏覽器的DOM對象遥巴,且可以隨意定義執(zhí)行時的 html 上下文千康。
測試結(jié)果應(yīng)當(dāng)可以直接反饋給 mocha,判斷測試是否通過铲掐。
瀏覽器環(huán)境執(zhí)行
我們首先搭建一個測試原型拾弃,用 mocha 自帶的腳手架可以自動生成。
cd vendor # 進入我們的項目文件夾
npm i -g mocha # 安裝全局的 mocha 命令行工具
mocha init . # 生成腳手架
mocha就會自動幫我們生成一個簡單的測試原型, 目錄結(jié)構(gòu)如下
.
├── index.html # 這是前端單元測試的入口
├── mocha.css
├── mocha.js
└── tests.js # 我們的單元測試代碼將在這里編寫
其中 index.html 是單元測試的入口摆霉,tests.js 是我們的測試用例文件豪椿。
我們直接在 index.html 插入上述示例的 fibonacci 函數(shù)以及斷言庫 chaijs。
<div id="mocha"></div>
<script src='https://cdn.rawgit.com/chaijs/chai/master/chai.js'></script>
<script>
var fibonacci = function (n) {
if (n === 0) {
return 0;
}
if (n === 1) {
return 1;
}
return fibonacci(n-1) + fibonacci(n-2);
};
</script>
然后在tests.js中寫入對應(yīng)測試用例
var should = chai.should();
describe('simple test', function () {
it('should equal 0 when n === 0', function () {
window.fibonacci(0).should.equal(0);
});
});
這時打開index.html携栋,可以發(fā)現(xiàn)測試結(jié)果搭盾,我們完成了瀏覽器端的腳本測試(注意我們調(diào)用了 window 對象)
測試反饋
mocha沒有提供一個命令行的前端腳本測試環(huán)境(因為我們的腳本文件需要運行在瀏覽器環(huán)境中),因此我們使用phantomjs幫助我們搭建一個模擬環(huán)境婉支。不重復(fù)制造輪子鸯隅,這里直接使用mocha-phantomjs幫助我們在命令行運行測試。
首先安裝mocha-phantomjs
npm i -g mocha-phantomjs
然后在 index.html 的頁面下加上這段兼容代碼
<script>mocha.run()</script>
改為
<script>
if (window.initMochaPhantomJS && window.location.search.indexOf('skip') === -1) {
initMochaPhantomJS()
}
mocha.ui('bdd');
expect = chai.expect;
mocha.run();
</script>
這時候, 我們在命令行中運行
mocha-phantomjs index.html --ssl-protocol=any --ignore-ssl-errors=true
結(jié)果展現(xiàn)是不是和后端代碼測試很類似 :smile:
更進一步,我們可以直接在 package.json 的 scripts 中添加
(package.json 通過 npm init
生成蝌以,這里不再贅述)
"scripts": {
"test": "mocha-phantomjs index.html --ssl-protocol=any --ignore-ssl-errors=true"
},
將mocha-phantomjs作為依賴
npm i mocha-phantomjs --save-dev
直接運行
npm test
運行結(jié)果如下:
至此,我們實現(xiàn)了前端腳本的單元測試炕舵,基于 phanatomjs 你幾乎可以調(diào)用所有的瀏覽器方法,而 mocha-phanatomjs 也可以很便捷地將測試結(jié)果反饋到 mocha跟畅,便于后續(xù)的持續(xù)集成咽筋。