鍍金池/ 教程/ HTML/ 瀏覽器端測試:mocha,chai,phantomjs
瀏覽器端測試:mocha,chai,phantomjs
搭建 Node.js 開發(fā)環(huán)境
測試用例:mocha,should,istanbul
線上部署:heroku
Mongodb 與 Mongoose 的使用
使用 superagent 與 cheerio 完成簡單爬蟲
js 中的那些最佳實踐
使用 eventproxy 控制并發(fā)
使用 promise 替代回調(diào)函數(shù)
作用域與閉包:this,var,(function () {})
持續(xù)集成平臺:travis
測試用例:supertest
benchmark 怎么寫
使用 async 控制并發(fā)
學(xué)習(xí)使用外部模塊
一個最簡單的 express 應(yīng)用
正則表達(dá)式
cookie 和 session

瀏覽器端測試:mocha,chai,phantomjs

目標(biāo)

建立一個 lesson7 項目,在其中編寫代碼。

main.js: 類似上文提到的 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;

vendor文件夾: 前端單元測試的環(huán)境。

vendor/tests.js 編寫針對前端腳本的測試用例

知識點

  1. 學(xué)習(xí)使用測試框架 mocha 進(jìn)行前端測試 : http://mochajs.org/
  2. 了解全棧的斷言庫 chai: http://chaijs.com/
  3. 了解 headless 瀏覽器 phantomjs: http://phantomjs.org/

前端腳本單元測試

[lesson6](https://github.com/alsotang/node-lessons/tree/master/lesson6 ) 的內(nèi)容都是針對后端環(huán)境中 node 的一些單元測試方案,出于應(yīng)用健壯性的考量,針對前端 js 腳本的單元測試也非常重要。而前后端通吃,也是 mocha 的一大特點。

首先,前端腳本的單元測試主要有兩個困難需要解決。

  1. 運行環(huán)境應(yīng)當(dāng)在瀏覽器中,可以操縱瀏覽器的DOM對象,且可以隨意定義執(zhí)行時的 html 上下文。

  2. 測試結(jié)果應(yīng)當(dāng)可以直接反饋給 mocha,判斷測試是否通過。

瀏覽器環(huán)境執(zhí)行

我們首先搭建一個測試原型,只需要執(zhí)行

//f2e 是原型生成的目錄
mocha init f2e

mocha就會自動幫我們生成一個簡單的測試原型

.
├── index.html
├── mocha.css
├── mocha.js
└── tests.js

其中 index.html 是單元測試的入口,tests.js 是我們的測試用例文件。

我們直接在 index.html 插入上述示例的 fibonacci 函數(shù)以及斷言庫 chaijs。

<div id="mocha"></div>
<script src='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 對象)

http://wiki.jikexueyuan.com/project/node-lessons/images/7-1.png" alt="" />

測試反饋

mocha沒有提供一個命令行的前端腳本測試環(huán)境(因為我們的腳本文件需要運行在瀏覽器環(huán)境中),因此我們使用phanatomjs幫助我們搭建一個模擬環(huán)境。不重復(fù)制造輪子,這里直接使用mocha-phantomjs幫助我們在命令行運行測試。

首先安裝mocha-phanatomjs

npm i -g mocha-phantomjs

然后將index.html對應(yīng)部分修改為

<script>
  if (window.mochaPhantomJS) { mochaPhantomJS.run(); }
  else { mocha.run(); }
</script>

然后我們在命令行中運行

mocha-phantomjs index.html

結(jié)果展現(xiàn)是不是和后端代碼測試很類似 :smile:

你也可以直接在package.json中定義

"scripts": {
  "test": "./node_modules/.bin/mocha-phantomjs vendor/index.html"
},

將mocha-phantomjs作為依賴

npm i mocha-phantomjs --save-dev

直接運行

npm test

至此,我們實現(xiàn)了前端腳本的單元測試,基于 phanatomjs 你幾乎可以調(diào)用所有的瀏覽器方法,而 mocha-phanatomjs 也可以很便捷地將測試結(jié)果反饋到 mocha,便于后續(xù)的持續(xù)集成。