美文网首页我爱编程
JavaScript自动集成化测试

JavaScript自动集成化测试

作者: 茂茂爱吃鱼 | 来源:发表于2018-07-24 14:41 被阅读0次

    观察程序员把时间耗在哪里,其实编码只占据很小的一部分,最多的时间则花在了调试上,有时甚至为了找出一个小问题不惜花费好几个小时来调试定位。如果在编码开始就为每一个功能编写相应测试,虽然每次需要花费额外的时间精力来编写测试,但一旦测试代码运行正常,工作就可以结束了,不需要再额外花费时间到调试代码上。因此,引入单元测试是有必要的?(实际开发中我其实没见过谁写过测试:joy:)

    单元测试是什么?

    在计算机编程中,单元测试(英语:Unit Testing)又称为模块测试, 是针对程序模块(软件设计的最小单位)来进行正确性检验的测试工作。 程序单元是应用的最小可测试部件。

    Node.js 单元测试框架

    比较受欢迎的单元测试框架有Jasmine,Mocha,Jest,AVA,Tape。Jasmine开箱即用,无需断言库;Mocha应该是使用人数最多的框架,需要导入其他库来实现断言功能;Jest广泛应用于测试React应用;AVA利用JS异步特性和并发运行测试,性能有所提高;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用法

    命令行执行测试脚本:

    $ mocha 'filename.{test|spec}.js'
    指定测试脚本时,可以使用通配符,同时指定多个文件(支持node与shell通配符)

    浏览器执行测试脚本:

    执行$ mocha init生成index.html及配套css、js,添加mocha.setup配置并引入should.js及测试脚本,末尾添加mocha.run(),浏览器打开index.html就可以看到测试脚本的执行结果

    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 (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块执行时需要传入done参数,当测试结束时,必须显式调用这个done函数,告诉Mocha测试结束了,否则,Mocha会一直等到超时报错。

    Promise

    Mocha内置对Promise的支持,允许直接返回Promise,等到它的状态改变,再执行断言,而不用显式调用done函数

    Mocha提供的钩子及测试脚本管理

    钩子:

    • before 在该test suite内所有test case之前运行
    • after 在该test suite内所有test case之后运行
    • beforeEach 在该test suite内每个test case之后运行
    • afterEach 在该test suite内每个test case之后运行

    脚本管理:

    • describe.only/it.only 只运行带only的test suite/test case
    • describe.skip/it.skip 跳过带skip的test suite/test case

    参考:
    Mocha 文档
    阮一峰Mocha教程

    相关文章

      网友评论

        本文标题:JavaScript自动集成化测试

        本文链接:https://www.haomeiwen.com/subject/ovmjmftx.html