mocha学习笔记2

测试持续时间

在测试报告里面,测试时间会被展示出来;如果时间过长,也会被标记出来。

使用this.slow(time)可以告诉Mocha该测试执行了多少时间才会被认为是一个耗时过长(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,然后测试执行时间都没有超过,所以测试可以通过

➜  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显示出期望值和实际值的对比区别。

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命令和参数使用

mocha --help会显示下面的内容,包含了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用来监测测试文件的变化,一旦变化被监测到,立即执行测试
  • mocha -b/mocha --bail 只对第一个抛出的异常进行处理。只要有一个测试用例没有通过,后面的测试用例也不会执行了
  • mocha -d/mocha --debug 开启node的debug模式,能够对标记了debugger语句的代码进行调试
  • 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指定测试用例执行时间为慢的阈值。默认是75毫秒。Mocha使用这个设置来标识那些运行时间很长的测试
  • mocha -g <pattern>/mocha --global <pattern>指定mocha去跑匹配描述和<pattern>一样的测试用例。类似于给测试用例打标签的作用
  • mocha --recursive test目录下面所有的测试用例都会执行,不止是第一层

接口风格类型

Mocha的接口风格可以让开发人员选择DSL的不同风格。现在有下面五种风格:

  • BDD
    • 提供 describe(), context(), it(), specify(), before(), after(), beforeEach()和afterEach()
    • describe() = context(), it() = specify()
  • TDD
    • 提供suite(), test(), suiteSetup(), suiteTeardown(), setup()和teardown()
  • Exports
    • 类似于mocha前身expresso
    • 测试套件是对象,函数是测试用例
  • QUnit
    • 类似QUnit。测试套件单独定义在测试用例之前
    • 像TDD一样支持suite()test()
    • 像BDD一样支持hooks
  • Require
    • 允许通过require()来导入describe()it()的方法
    • 可以自己定义别名
    • 只能用mocha命令执行,node不行

报告

Mocha提供了多种console端报告模式

  • mocha --reporter spec这是默认模式。是一个按照测试套件和用例分层次的视图
  • mocha --reporter dot显示一个由点组成的矩阵。点的颜色代表着不同的测试结果
  • 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的选项参数,做到简化选项配置管理。注意是要在test目录下面。如果命令行也有参数的话,此命令行参数优先。

文件的内容可如下所示

--require should
--reporter dot
--ui bdd

如果写为

dir-test
--recursive

表明指定运行dir-test目录及其子目录之中的测试脚本

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,911评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,014评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 142,129评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,283评论 1 264
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,159评论 4 357
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,161评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,565评论 3 382
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,251评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,531评论 1 292
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,619评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,383评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,255评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,624评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,916评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,199评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,553评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,756评论 2 335

推荐阅读更多精彩内容