学习js测试框架-Mocha

1,973 阅读5分钟

这是我参与8月更文挑战的第7天,活动详情查看: 8月更文挑战

前言

学习一个新知识点,要知道ta 是什么(what),在哪用(where),为什么(why),怎么用(how)!

Mocha(发音"摩卡")诞生于2011年,是现在最流行的JavaScript测试框架之一,在浏览器和Node环境都可以使用。

所谓"测试框架",就是运行测试的工具。通过它,可以为JavaScript应用添加测试,从而保证代码的质量。

优点

Mocha是一个功能丰富的javascript测试框架,运行在node.js和浏览器中,使异步测试变得简单有趣。Mocha测试连续运行,允许灵活和准确的报告,同时将未捕获的异常映射到正确的测试用例。

安装

npm全局安装

npm install --global mocha

或者只在项目中安装

npm install --save-dev mocha

也可以在packjson中写上依赖然后安装依赖。

查看版本 看是否安装成功

mocha --version

image.png

安装较为简单,我们简单学习然后直接上例子

先简单学习

测试脚本结构:

describe('加法函数的测试', function () {
  it('11应该等于2', function () {
    expect(add(1, 1)).to.be.equal(2);
  });
});

describe

测试脚本里面应该包括一个或多个describe块,每个describe块应该包括一个或多个it块。

describe块称为"测试套件"(test suite),表示一组相关的测试。它是一个函数,第一个参数是测试套件的名称("加法函数的测试"),第二个参数是一个实际执行的函数。

it块称为"测试用例"(test case),表示一个单独的测试,是测试的最小单位。它也是一个函数,第一个参数是测试用例的名称("1加1应该等于 2"),第二个参数是一个实际执行的函数。

expect则是断言,所谓"断言",就是判断源码的实际执行结果与预期结果是否一致,如果不一致就抛出一个错误。上面这句断言的意思是,调用add(1, 1),结果应该等于2。

断言

Mocha允许你使用任意你喜欢的断言库。如果能够抛出一个错误,它就能够运行。这意味着你能使用下面的这些仓库,比如:

直接来写个简单例子:

例子

新建个demo.js文件,简单实现加减乘除四个函数,并导出

function add(x, y) {
  return x + y;
}
function reduce(x, y) {
  return x - y;
}
function multiply(x, y) {
  return x * y;
}
function divide(x, y) {
  return x / y;
}

module.exports = { add, reduce, multiply, divide }

然后再同级目录新建个demo.test.js测试文件,写四个测试例子

var { add, reduce, multiply, divide } = require('./add.js');
var expect = require('chai').expect;

describe('加法函数的测试', function () {
  it('11应该等于2', function () {
    expect(add(1, 1)).to.be.equal(2);
  });
});
describe('减法函数的测试', function () {
  it('31等于2', function () {
    expect(reduce(3, 1)).to.be.equal(2);
  });
});
describe('乘法函数的测试', function () {
  it('2乘以2等于4', function () {
    expect(multiply(2, 2)).to.be.equal(4);
  });
});
describe('除法函数的测试', function () {
  it('8除以2等于4', function () {
    expect(divide(8, 2)).to.be.equal(4);
  });
});

然后执行测试mocha demo.test.js

image.png

如果是测试结果不对的情况:

image.png

命令

用法 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
    --file <file>                           include a file to be ran during the suite [file]
    --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

(取自官网,6级没过,就不翻译了)

image.png

学习链接

放几个学习Mocha的链接

小结

以上说了一下Mocha的简单安装和一些简单例子的测试。Mocha的功能可不单单这些,还有异步代码、同步代码、钩子等知识点。 我也在继续学习中,且学且记录。

如果你还有补充或者说明的欢迎留言评论。

熟能生巧(Practice make perfect!)。

567570eb04c107f0a5d6ccf93447999.png