Table of Contents
Related technologies for testing
Configure the test environment for nodejs project
1 Install the corresponding dependency packages
2 配置Istanbul
编写测试代码
1 一段简单的mocha测试代码
2 用Sinon模拟文件读写
持续集成
Home Web Front-end JS Tutorial mocha, chai, sinon and istanbul achieve 100% unit test coverage

mocha, chai, sinon and istanbul achieve 100% unit test coverage

Jul 10, 2017 pm 06:10 PM
mocha

In agile software development, the most important practice is test-driven development. At the unit testing level, an important indicator we try to achieve is test coverage. Test coverage measures whether all of our code has been tested.

But the indicator itself is not the purpose. With the help of test coverage check, we hope to find those codes that are not covered by tests, so as to think about how to test the logic of those codes, and then better design and refactor the code to make the code more efficient. quality[1].

Speaking of testing, I happened to be reading "The Beauty of Mathematics" recently, and there was a passage about information in the book. The same goes for changing the behavior of code from nondeterministic to deterministic. From a black box to a white box, there is no magic power. It can only provide enough information. The assertions in the test are information, and the test coverage is also information. The test coverage can be considered as a kind of indirect information, which can eliminate some of the information. Uncertainty, whereas full assertions provide more direct information. Coupled with test coverage checks, it can provide enough information to assert whether the code behaves as expected.

Istanbul is a code coverage tool for the JavaScript program, named after Istanbul, the largest city in Turkey. Istanbul will convert the code, generate a syntax tree, and then inject statistical code at the corresponding location. After execution, the number of code executions will be counted based on the value of the injected global variable; after the code conversion is completed, Istanbul will call test runner, such as mocha, executes the test of the converted code and generates a test report.

Mocha is a testing framework, which is a tool for running tests, similar to Jasmine, Karma and Ava. Like JUnit's annotations, mocha serves as an executor and uses the descibe and it methods to define test suits and group different tests. Mocha itself does not provide assert assertions, so to provide more expressive assertions, you can use it with chai. Of course, you can also use the assert module provided by nodejs. .

In our code, there will always be some complex logic or asynchronous code that relies on io and network, which is difficult to test using direct methods. In this case, we can simplify the testing of complex code through sinon. Sinon replaces some functions or classes that our code depends on with test doubles by creating Test Double, which is Test Double, and we can set the behavior of the test double to simulate the results required by our code. , allowing difficult-to-test code logic to be executed.

Configure the test environment for nodejs project

1 Install the corresponding dependency packages

Mocha and istanbul can be installed globally or only in the current project.

<code class="q">npm install --<span class="hljs-built_in">save-<span class="hljs-built_in">dev mocha chai sinon istanbul</span></span></code>
Copy after login

After the installation is complete, under the scripts of the package.json file, add commands to execute tests and test coverage checks

<code class="json">{
  ...
  <span class="hljs-attr">"scripts":{
    <span class="hljs-attr">"coverage": <span class="hljs-string">"istanbul cover _mocha -- -R spec --timeout 5000 --recursive",
    <span class="hljs-attr">"coverage:check": <span class="hljs-string">"istanbul check-coverage",
  }
  ...
}</span></span></span></span></span></code>
Copy after login

Run npm run coverage and npm run coverage:check to generate a test report. The former generates a test report, and the latter checks whether the test coverage meets the requirements.

2 配置Istanbul

istanbul相关的执行参数,可以在命令行下执行时传递参数来制定,也可以在yaml格式的.istanbul.yml文件中配置。简单贴出一些重要的配置项

<code class="yaml"><span class="hljs-attr">instrumentation:
<span class="hljs-attr">  root: .   <span class="hljs-comment"># 执行的根目录
<span class="hljs-attr">  extensions:
<span class="hljs-bullet">    - .js   <span class="hljs-comment"># 检查覆盖率的文件扩张名
<span class="hljs-attr">  excludes: [<span class="hljs-string">'**/benchmark/**']

  ... ...

<span class="hljs-attr">reporting:
<span class="hljs-attr">  print: summary
<span class="hljs-attr">  reports: [lcov, text, html, text-summary] <span class="hljs-comment"># 生成报告的格式
<span class="hljs-attr">  dir: ./coverage   <span class="hljs-comment"># 生成报告保存的目录
<span class="hljs-attr">  watermarks:       <span class="hljs-comment"># 在不同覆盖率下会显示使用不同颜色
<span class="hljs-attr">    statements: [<span class="hljs-number">80, <span class="hljs-number">95]
    ... ...
<span class="hljs-attr">check:
<span class="hljs-attr">  global:
<span class="hljs-attr">    statements: <span class="hljs-number">100
<span class="hljs-attr">    branches: <span class="hljs-number">100
<span class="hljs-attr">    lines: <span class="hljs-number">100
<span class="hljs-attr">    functions: <span class="hljs-number">100</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></code>
Copy after login

最后的check是项目要通过覆盖率检查需要达到的测试覆盖率,测试覆盖率包括四个维度,分别是语句覆盖率、分支覆盖率、行覆盖率和函数覆盖率。如果达不到设定的指标,在执行的时候会报错,项目的测试就无法通过自动化的持续集成。

编写测试代码

敏捷软件开发中的测试驱动开发,意在通过先写测试,根据调用者的契约,设计如何实现代码,从而写出更加容易测试的代码,提高代码的质量。也是我们练习测试的应该考虑的方向。

1 一段简单的mocha测试代码

利用chai提供的expect断言,我们可以用BDD的方式,写出更加符合代码预期行为的测试用例。

<code class="javascript"><span class="hljs-keyword">var chai = <span class="hljs-built_in">require(<span class="hljs-string">'chai')

chai.should()
<span class="hljs-keyword">var expect = chai.expect
<span class="hljs-keyword">var assert = chai.assert

describe(<span class="hljs-string">'basic test', <span class="hljs-function"><span class="hljs-keyword">function (<span class="hljs-params">) {
  describe(<span class="hljs-string">'simple', <span class="hljs-function"><span class="hljs-keyword">function (<span class="hljs-params">) {
    it(<span class="hljs-string">'data check', <span class="hljs-function"><span class="hljs-keyword">function (<span class="hljs-params">) {
      <span class="hljs-keyword">var data = { <span class="hljs-attr">name: <span class="hljs-string">"test" }

      assert.isNotNull(data, <span class="hljs-string">'data should not be null')
      expect(data).to.be.an(<span class="hljs-string">'object')
      expect(data).to.have.all.keys([<span class="hljs-string">'name'])
      expect(data).to.deep.include({<span class="hljs-attr">name: <span class="hljs-string">'test'});
    });
  });
});</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></code>
Copy after login

2 用Sinon模拟文件读写

<code class="javascript">... 同上 ...
var sinon = <span class="hljs-built_in">require(<span class="hljs-string">'sinon')
<span class="hljs-keyword">var fs = <span class="hljs-built_in">require(<span class="hljs-string">'fs')

describe(<span class="hljs-string">'sinon', <span class="hljs-function"><span class="hljs-keyword">function (<span class="hljs-params">) {
  it(<span class="hljs-string">"should mock readFile", <span class="hljs-function"><span class="hljs-keyword">function(<span class="hljs-params">done){
    sinon.stub(fs, <span class="hljs-string">'readFile').callsFake(<span class="hljs-function"><span class="hljs-keyword">function (<span class="hljs-params">path, callback) { callback(<span class="hljs-keyword">new <span class="hljs-built_in">Error(<span class="hljs-string">'read error')) })

    fs.readFile(<span class="hljs-string">"any file path", <span class="hljs-function"><span class="hljs-keyword">function(<span class="hljs-params">err,data){
      assert.isNotNull(err)
      done()
    })
    assert(fs.readFile.calledOnce)
  });
});</span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></code>
Copy after login

在mocha测试框架中,如果我们调用的是异步的代码,那么需要显示的调用it回调函数的done方法,告诉mocha异步调用什么时候结束。否则的话,测试会挂起,直到设置的超时时间结束。

Sinon将测试替身分为spy、stub和mock,其中:

  • Spy, 可以提供函数调用的信息,但不会改变函数的行为
  • Stub, 提供函数的调用信息,并且可以像示例代码中一样,让被stubbed的函数返回任何我们需要的行为。
  • Mock, 通过组合spies和stubs,使替换一个完整对象更容易。

本文的讨论篇幅有限,暂时不详细介绍各种sinon的使用方法,以后再通过其他文章专门介绍。

持续集成

完成所有代码之后,我们可以将代码发布到github,然后使用持续集成工具travis检查代码,将生成的测试报告上传到coverall上,这样就可以在项目中显示项目状态和测试覆盖率的badges。

具体使用方法,可以参看官方网站,使用coveralls需要在项目中安装依赖包npm i -D coveralls。并且添加package.json执行脚本istanbul cover ./node_modules/mocha/bin/_mocha --report lcovonly -- -R spec && cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js

通常的nodejs项目.travis.yml配置如下:

<code class="yaml"><span class="hljs-attr">language: node_js
<span class="hljs-attr">node_js:
<span class="hljs-bullet">  - <span class="hljs-string">"7.6.0"
<span class="hljs-attr">install:
<span class="hljs-bullet">  - npm install
<span class="hljs-attr">script:
<span class="hljs-bullet">  - npm test
<span class="hljs-attr">after_script:
<span class="hljs-bullet">  - npm run coverall</span></span></span></span></span></span></span></span></span></span></code>
Copy after login

 

 

原文地址:http://www.51test.space/archives/2543

The above is the detailed content of mocha, chai, sinon and istanbul achieve 100% unit test coverage. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1667
14
PHP Tutorial
1273
29
C# Tutorial
1255
24
JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript in Action: Real-World Examples and Projects JavaScript in Action: Real-World Examples and Projects Apr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding the JavaScript Engine: Implementation Details Understanding the JavaScript Engine: Implementation Details Apr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Python vs. JavaScript: Development Environments and Tools Python vs. JavaScript: Development Environments and Tools Apr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

See all articles