search
HomeWeb Front-endJS Tutorialmocha, chai, sinon and istanbul achieve 100% unit test coverage

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>

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>

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>

最后的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>

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>

在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>

 

 

原文地址: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
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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

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

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft