JavaScript自動集成化測試

觀察程序員把時間耗在哪里慈省,其實編碼只占據(jù)很小的一部分瓮恭,最多的時間則花在了調(diào)試上,有時甚至為了找出一個小問題不惜花費好幾個小時來調(diào)試定位。如果在編碼開始就為每一個功能編寫相應測試嫌蚤,雖然每次需要花費額外的時間精力來編寫測試市袖,但一旦測試代碼運行正常咙鞍,工作就可以結束了苞冯,不需要再額外花費時間到調(diào)試代碼上。因此肯尺,引入單元測試是有必要的?(實際開發(fā)中我其實沒見過誰寫過測試:joy:)

單元測試是什么沃缘?

在計算機編程中,單元測試(英語:Unit Testing)又稱為模塊測試, 是針對程序模塊(軟件設計的最小單位)來進行正確性檢驗的測試工作蟆盹。 程序單元是應用的最小可測試部件孩灯。

Node.js 單元測試框架

比較受歡迎的單元測試框架有Jasmine,Mocha逾滥,Jest峰档,AVA败匹,Tape。Jasmine開箱即用讥巡,無需斷言庫掀亩;Mocha應該是使用人數(shù)最多的框架,需要導入其他庫來實現(xiàn)斷言功能欢顷;Jest廣泛應用于測試React應用槽棍;AVA利用JS異步特性和并發(fā)運行測試,性能有所提高抬驴;Tape比較小炼七,搭建運行比較簡潔,無需過多的配置布持,支持TypeScript/CoffeeScript/ES6豌拙。本文主要介紹下Mocha。

斷言庫

由于Mocha本身沒有斷言功能题暖,需要選擇一款斷言庫搭配使用按傅。與Mocha搭配的斷言庫主要有5種(should.js/chai/expect.js/better-assert/unexpected),本文使用的是TJ大神的should.js胧卤,該斷言庫更加類似于自然語言的寫法唯绍。

Mocha測試腳本基本結構

  • describe 測試套件(test suite)一組相關的測試
  • it 測試用例(test case)測試的最小單元
    測試腳本應包括一個或多個describe,每個describe塊應包括一個或多個it塊

Mocha用法

命令行執(zhí)行測試腳本:

$ mocha 'filename.{test|spec}.js'
指定測試腳本時枝誊,可以使用通配符况芒,同時指定多個文件(支持node與shell通配符)

瀏覽器執(zhí)行測試腳本:

執(zhí)行$ mocha init生成index.html及配套css、js叶撒,添加mocha.setup配置并引入should.js及測試腳本牛柒,末尾添加mocha.run(),瀏覽器打開index.html就可以看到測試腳本的執(zhí)行結果

Mocha命令行參數(shù)

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 (default: spec)
-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) (default: bdd)
-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 (default: )
--debug-brk                             enable node's debugger breaking on the first line
--globals <names>                       allow the given comma-delimited global [names] (default: )
--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
--no-diff                               do not show a diff on failure
--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 (default: test/mocha.opts)
--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>,...            specify extensions to monitor with --watch (default: js)
--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
--file <file>                           include a file to be ran during the suite (default: )
--exclude <file>                        a file or glob pattern to ignore (default: )
-h, --help                              output usage information

Commands:

init <path>  initialize a client-side mocha setup at <path>

Mocha異步測試

callback方式

it塊執(zhí)行時需要傳入done參數(shù),當測試結束時椭更,必須顯式調(diào)用這個done函數(shù)哪审,告訴Mocha測試結束了,否則虑瀑,Mocha會一直等到超時報錯湿滓。

Promise

Mocha內(nèi)置對Promise的支持,允許直接返回Promise舌狗,等到它的狀態(tài)改變叽奥,再執(zhí)行斷言,而不用顯式調(diào)用done函數(shù)

Mocha提供的鉤子及測試腳本管理

鉤子:

  • before 在該test suite內(nèi)所有test case之前運行
  • after 在該test suite內(nèi)所有test case之后運行
  • beforeEach 在該test suite內(nèi)每個test case之后運行
  • afterEach 在該test suite內(nèi)每個test case之后運行

腳本管理:

  • describe.only/it.only 只運行帶only的test suite/test case
  • describe.skip/it.skip 跳過帶skip的test suite/test case

參考:
Mocha 文檔
阮一峰Mocha教程

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末痛侍,一起剝皮案震驚了整個濱河市朝氓,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖赵哲,帶你破解...
    沈念sama閱讀 217,657評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件待德,死亡現(xiàn)場離奇詭異,居然都是意外死亡枫夺,警方通過查閱死者的電腦和手機将宪,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評論 3 394
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來橡庞,“玉大人较坛,你說我怎么就攤上這事“亲睿” “怎么了丑勤?”我有些...
    開封第一講書人閱讀 164,057評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長扼倘。 經(jīng)常有香客問我确封,道長,這世上最難降的妖魔是什么再菊? 我笑而不...
    開封第一講書人閱讀 58,509評論 1 293
  • 正文 為了忘掉前任爪喘,我火速辦了婚禮,結果婚禮上纠拔,老公的妹妹穿的比我還像新娘秉剑。我一直安慰自己,他們只是感情好稠诲,可當我...
    茶點故事閱讀 67,562評論 6 392
  • 文/花漫 我一把揭開白布侦鹏。 她就那樣靜靜地躺著,像睡著了一般臀叙。 火紅的嫁衣襯著肌膚如雪略水。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,443評論 1 302
  • 那天劝萤,我揣著相機與錄音渊涝,去河邊找鬼。 笑死床嫌,一個胖子當著我的面吹牛跨释,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播厌处,決...
    沈念sama閱讀 40,251評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼鳖谈,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了阔涉?” 一聲冷哼從身側(cè)響起缆娃,我...
    開封第一講書人閱讀 39,129評論 0 276
  • 序言:老撾萬榮一對情侶失蹤捷绒,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后龄恋,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體疙驾,經(jīng)...
    沈念sama閱讀 45,561評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,779評論 3 335
  • 正文 我和宋清朗相戀三年郭毕,在試婚紗的時候發(fā)現(xiàn)自己被綠了它碎。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,902評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡显押,死狀恐怖扳肛,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情乘碑,我是刑警寧澤挖息,帶...
    沈念sama閱讀 35,621評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站兽肤,受9級特大地震影響套腹,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜资铡,卻給世界環(huán)境...
    茶點故事閱讀 41,220評論 3 328
  • 文/蒙蒙 一电禀、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧笤休,春花似錦尖飞、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,838評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至闹啦,卻和暖如春沮明,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背窍奋。 一陣腳步聲響...
    開封第一講書人閱讀 32,971評論 1 269
  • 我被黑心中介騙來泰國打工珊擂, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人费变。 一個月前我還...
    沈念sama閱讀 48,025評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像圣贸,于是被迫代替她去往敵國和親挚歧。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,843評論 2 354

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