mocha學習筆記2

測試持續(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.expectederr.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目錄及其子目錄之中的測試腳本

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市蚂且,隨后出現(xiàn)的幾起案子配猫,更是在濱河造成了極大的恐慌,老刑警劉巖杏死,帶你破解...
    沈念sama閱讀 217,277評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件泵肄,死亡現(xiàn)場離奇詭異,居然都是意外死亡淑翼,警方通過查閱死者的電腦和手機腐巢,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評論 3 393
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來玄括,“玉大人冯丙,你說我怎么就攤上這事≡饩” “怎么了胃惜?”我有些...
    開封第一講書人閱讀 163,624評論 0 353
  • 文/不壞的土叔 我叫張陵泞莉,是天一觀的道長。 經(jīng)常有香客問我船殉,道長鲫趁,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,356評論 1 293
  • 正文 為了忘掉前任捺弦,我火速辦了婚禮饮寞,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘列吼。我一直安慰自己幽崩,他們只是感情好,可當我...
    茶點故事閱讀 67,402評論 6 392
  • 文/花漫 我一把揭開白布寞钥。 她就那樣靜靜地躺著慌申,像睡著了一般。 火紅的嫁衣襯著肌膚如雪理郑。 梳的紋絲不亂的頭發(fā)上蹄溉,一...
    開封第一講書人閱讀 51,292評論 1 301
  • 那天,我揣著相機與錄音您炉,去河邊找鬼柒爵。 笑死,一個胖子當著我的面吹牛赚爵,可吹牛的內(nèi)容都是我干的棉胀。 我是一名探鬼主播,決...
    沈念sama閱讀 40,135評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼冀膝,長吁一口氣:“原來是場噩夢啊……” “哼唁奢!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起窝剖,我...
    開封第一講書人閱讀 38,992評論 0 275
  • 序言:老撾萬榮一對情侶失蹤麻掸,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后赐纱,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體脊奋,經(jīng)...
    沈念sama閱讀 45,429評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,636評論 3 334
  • 正文 我和宋清朗相戀三年疙描,在試婚紗的時候發(fā)現(xiàn)自己被綠了狂魔。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,785評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡淫痰,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出整份,到底是詐尸還是另有隱情待错,我是刑警寧澤籽孙,帶...
    沈念sama閱讀 35,492評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站火俄,受9級特大地震影響犯建,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜瓜客,卻給世界環(huán)境...
    茶點故事閱讀 41,092評論 3 328
  • 文/蒙蒙 一适瓦、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧谱仪,春花似錦玻熙、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至敬尺,卻和暖如春枚尼,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背砂吞。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評論 1 269
  • 我被黑心中介騙來泰國打工署恍, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人蜻直。 一個月前我還...
    沈念sama閱讀 47,891評論 2 370
  • 正文 我出身青樓盯质,卻偏偏與公主長得像,于是被迫代替她去往敵國和親袭蝗。 傳聞我的和親對象是個殘疾皇子唤殴,可洞房花燭夜當晚...
    茶點故事閱讀 44,713評論 2 354

推薦閱讀更多精彩內(nèi)容