應該先了解最核心的斷言模塊/庫,而後結合現有的測試框架和管理工具進行開發測試用例。javascript
所謂"斷言",就是判斷源碼的實際執行結果與預期結果是否一致,若是不一致就拋出一個錯誤。 經常使用的斷言庫有assert、should.js、chai.jshtml
assert.deepStrictEqual(actual,expected[,message])前端
對比actual和expected參數是否深度相等。便可枚舉屬性也會按照規則比較。java
const assert = require('assert');
let a = {
b: 1
}
let b = {
b: 2
}
assert.deepStrictEqual(a,b,'budui')
複製代碼
最關鍵的是最後一行代碼,當比較的兩個對象不深度相等時,則Assert拋出錯誤node
AssertionError [ERR_ASSERTION]: 對象不相等 at Object.git
用法上其實和assert差很少。api相對較多。具體參考官網。github
實際業務測試中,優秀的測試框架必不可少,有Mocha、Jasmine、Tape、jest等ajax
describe('addTest', function () {
it('0.1加上0.2等於0.3', function () {
// 使用should.js斷言
add(0.1, 0.2).should.equal(0.3)
})
})
複製代碼
Mocha 測試用例如上,主要包含下面幾部分:typescript
describe 定義的測試套件(test suite),第一個參數是套件名稱,第二個參數是一個函數npm
it 定義的測試用例(test case),第一個參數是用例名稱,第二個參數是一個函數。
一個describe裏能夠有多個it
默認每一個測試用例最多執行2000毫秒,可使用-t參數指定超時時間
mocha -t 5000 test.js
it('should able to request https://api.github.com/', function (done) {
// 使用 jQuery.ajax 請求
$.ajax({
url:"https://api.github.com/",
success: function() {
done()
}
})
})
複製代碼
異步測試時,須要在異步完成後加入done()告訴mocha測試結束。不然會一直等待,超時報錯。
在describe中調用
mocha還有其餘不少功能,如
監視指定測試用例,自動執行(mocha -w)
用例管理(only,skip)
...
只需前往Mocha查看文檔
參考: 測試框架 Mocha 實例教程
Which testing framework do you want to use? Press tab to list possible options. Enter to move to the next question.
mocha
Do you want to use Require.js? This will add Require.js plugin. Press tab to list possible options. Enter to move to the next question.
no
Do you want to capture a browser automatically? Press tab to list possible options. Enter empty string to move to the next question.
Chrome Firefox
What is the location of your source and test files? You can use glob patterns, eg. "js/*.js" or "test/**/*Spec.js". Press Enter to move to the next question.
node_modules/should/should.js test/**/*.js
Should any of the files included by the previous patterns be excluded? You can use glob patterns, eg. "**/*.swp". Press Enter to move to the next question.
Do you want Karma to watch all the files and run the tests on change? Press tab to list possible options.
yes
完成後會在項目根目錄生成配置文件 karma.conf.js
持續集成指的是隻要代碼有變動,就自動運行構建和測試,反饋運行結果。
這裏我採用了Travis CI
每次提交代碼之後會根據配置文件的跑測試用例。不管是否跑通,都會有相應的報告。
參考: