測試持續(xù)時間
在測試報告里面百侧,測試時間會被展示出來砰识;如果時間過長,也會被標記出來佣渴。
使用this.slow(time)
可以告訴Mocha
該測試執(zhí)行了多少時間才會被認為是一個耗時過長(slow)的測試辫狼,從而需要高亮這個測試。
describe('something slow', function() {
this.slow(10000);
it('should take long enough for me to go make a sandwich', function() {
// ...
});
});
測試超時
通過在describe()
級別定義this.timeout(time_number)
辛润,這個超時時間將會作用于該測試套件下的子測試套件和測試用例膨处。
describe('a suite of tests', function() {
this.timeout(500);
it('should take less than 500ms', function(done){
setTimeout(done, 300);
});
it('should take less than 500ms as well', function(done){
setTimeout(done, 250);
});
})
上面的代碼定義了超時時間是500ms,然后測試執(zhí)行時間都沒有超過砂竖,所以測試可以通過
? mocha_demo mocha test.js
a suite of tests
? should take less than 500ms (304ms)
? should take less than 500ms as well (255ms)
2 passing (568ms)
如果我們試著把第一個用例的時間從300改為550真椿,我們就會得到下面這種超時錯誤
? mocha_demo mocha test.js
a suite of tests
1) should take less than 500ms
? should take less than 500ms as well (256ms)
1 passing (771ms)
1 failing
1) a suite of tests
should take less than 500ms:
Error: Timeout of 500ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
在it()
中使用this.timeout(0)
可以重載/消除測試套件定義的超時時間。
同理乎澄,在測試用例使用方法一樣
it('should take less than 500ms', function(done){
this.timeout(500);
setTimeout(done, 300);
});
在Hooks中使用如下
describe('a suite of tests', function() {
beforeEach(function(done) {
this.timeout(3000); // A very long environment setup.
setTimeout(done, 2500);
});
});
DIFF差異比較
當Mocha
捕捉到AssertionError且有err.expected
和err.actual
屬性的時候瀑粥,Mocha
會自動化在console顯示出期望值和實際值的對比區(qū)別。
const assert = require('assert');
describe('this is suite 1', function() {
it('this is test case 1', function(){
assert.equal(-1, [1,2,3].indexOf(0));
});
it('this is test case 2', function(){
assert.equal('test', [1,2,3].toString());
});
})
? mocha_demo mocha test.js
this is suite 1
? this is test case 1
1) this is test case 2
1 passing (12ms)
1 failing
1) this is suite 1
this is test case 2:
AssertionError [ERR_ASSERTION]: 'test' == '1,2,3'
+ expected - actual
-test
+1,2,3
at Context.<anonymous> (test.js:9:12)
Mocha命令和參數(shù)使用
mocha --help
會顯示下面的內(nèi)容三圆,包含了mocha
的全部命令以及簡單介紹
Usage: mocha [debug] [options] [files]
Options:
-V, --version output the version number
-A, --async-only force all tests to take a callback (async) or return a promise
-c, --colors force enabling of colors
-C, --no-colors force disabling of colors
-G, --growl enable growl notification support
-O, --reporter-options <k=v,k2=v2,...> reporter-specific options
-R, --reporter <name> specify the reporter to use
-S, --sort sort test files
-b, --bail bail after first test failure
-d, --debug enable node's debugger, synonym for node --debug
-g, --grep <pattern> only run tests matching <pattern>
-f, --fgrep <string> only run tests containing <string>
-gc, --expose-gc expose gc extension
-i, --invert inverts --grep and --fgrep matches
-r, --require <name> require the given module
-s, --slow <ms> "slow" test threshold in milliseconds [75]
-t, --timeout <ms> set test-case timeout in milliseconds [2000]
-u, --ui <name> specify user-interface (bdd|tdd|qunit|exports)
-w, --watch watch files for changes
--check-leaks check for global variable leaks
--full-trace display the full stack trace
--compilers <ext>:<module>,... use the given module(s) to compile files
--debug-brk enable node's debugger breaking on the first line
--globals <names> allow the given comma-delimited global [names]
--es_staging enable all staged features
--harmony<_classes,_generators,...> all node --harmony* flags are available
--preserve-symlinks Instructs the module loader to preserve symbolic links when resolving and caching modules
--icu-data-dir include ICU data
--inline-diffs display actual/expected differences inline within each string
--inspect activate devtools in chrome
--inspect-brk activate devtools in chrome and break on the first line
--interfaces display available interfaces
--no-deprecation silence deprecation warnings
--exit force shutdown of the event loop after test run: mocha will call process.exit
--no-timeouts disables timeouts, given implicitly with --debug
--no-warnings silence all node process warnings
--opts <path> specify opts path
--perf-basic-prof enable perf linux profiler (basic support)
--napi-modules enable experimental NAPI modules
--prof log statistical profiling information
--log-timer-events Time events including external callbacks
--recursive include sub directories
--reporters display available reporters
--retries <times> set numbers of time to retry a failed test case
--throw-deprecation throw an exception anytime a deprecated function is used
--trace trace function calls
--trace-deprecation show stack traces on deprecations
--trace-warnings show stack traces on node process warnings
--use_strict enforce strict mode
--watch-extensions <ext>,... additional extensions to monitor with --watch
--delay wait for async suite definition
--allow-uncaught enable uncaught errors to propagate
--forbid-only causes test marked with only to fail the suite
--forbid-pending causes pending tests and test marked with skip to fail the suite
-h, --help output usage information
Commands:
init <path> initialize a client-side mocha setup at <path>
可以看見Mocha
提供了非常多有用的功能。下面介紹一些主要使用的選項
-
mocha -w
/mocha --watch
用來監(jiān)測測試文件的變化避咆,一旦變化被監(jiān)測到舟肉,立即執(zhí)行測試 -
mocha -b
/mocha --bail
只對第一個拋出的異常進行處理。只要有一個測試用例沒有通過查库,后面的測試用例也不會執(zhí)行了 -
mocha -d
/mocha --debug
開啟node的debug模式路媚,能夠?qū)擞浟薲ebugger語句的代碼進行調(diào)試 -
mocha -R
/mocha --reporter
指定mocha提供的reporter形式或第三方reporter。默認是“spec” -
mocha -u
/mocha --ui
指定使用的測試接口樊销。默認是“bdd” -
mocha -t
/mocha --timeout
指定測試用例的超時時間整慎。默認是2s脏款。--timeout 2s
或是--timeout 2000
-
mocha -s
/mocha --slow
指定測試用例執(zhí)行時間為慢的閾值。默認是75毫秒裤园。Mocha
使用這個設(shè)置來標識那些運行時間很長的測試 -
mocha -g <pattern>
/mocha --global <pattern>
指定mocha
去跑匹配描述和<pattern>
一樣的測試用例撤师。類似于給測試用例打標簽的作用 -
mocha --recursive
test目錄下面所有的測試用例都會執(zhí)行,不止是第一層
接口風格類型
Mocha
的接口風格可以讓開發(fā)人員選擇DSL的不同風格∨±浚現(xiàn)在有下面五種風格:
- BDD
- 提供 describe(), context(), it(), specify(), before(), after(), beforeEach()和afterEach()
- describe() = context(), it() = specify()
- TDD
- 提供suite(), test(), suiteSetup(), suiteTeardown(), setup()和teardown()
- Exports
- 類似于
mocha
前身expresso
- 測試套件是對象剃盾,函數(shù)是測試用例
- 類似于
- QUnit
- 類似QUnit。測試套件單獨定義在測試用例之前
- 像TDD一樣支持
suite()
和test()
- 像BDD一樣支持hooks
- Require
- 允許通過
require()
來導入describe()
和it()
的方法 - 可以自己定義別名
- 只能用
mocha
命令執(zhí)行淤袜,node
不行
- 允許通過
報告
Mocha
提供了多種console端報告模式
-
mocha --reporter spec
這是默認模式痒谴。是一個按照測試套件和用例分層次的視圖 -
mocha --reporter dot
顯示一個由點組成的矩陣。點的顏色代表著不同的測試結(jié)果 -
mocha --reporter nyan
顯示了一個圖铡羡。积蔚。。烦周。尽爆。 -
mocha --reporter tap
基于Test Anything Protocol (TAP) -
mocha --reporter landing
模擬飛機降落 -
mocha --reporter list
以列表的形式顯示每一個測試用例 -
mocha --reporter progress
以進度條的形式顯示 -
mocha --reporter json
輸出json格式的報告 -
mocha --reporter min
只輸出summary÷鄯可以與mocha -w
一起使用 -
mocha --reporter doc
輸出HTML格式的報告 -
mocha --reporter markdown
輸出HTML格式的報告
除了console端的報告教翩,mochawesome會輸出一個漂亮的HTML文件。
mocha.opts
Mocha
允許在配置文件./test/mocha.opts
中寫入mocha
的選項參數(shù)贪壳,做到簡化選項配置管理饱亿。注意是要在test
目錄下面。如果命令行也有參數(shù)的話闰靴,此命令行參數(shù)優(yōu)先彪笼。
文件的內(nèi)容可如下所示
--require should
--reporter dot
--ui bdd
如果寫為
dir-test
--recursive
表明指定運行dir-test
目錄及其子目錄之中的測試腳本