Home  >  Article  >  Web Front-end  >  Detailed introduction to front-end unit testing framework-Mocha

Detailed introduction to front-end unit testing framework-Mocha

零下一度
零下一度Original
2017-06-26 11:23:181901browse

Introduction

With the emergence of the concept of front-end engineering, the amount of front-end code in project development can be said to have increased sharply. So in this case, how can we ensure the quality of the code? For frameworks, such as React and Vue, because they have their own grammatical rules, each developer's coding style specifications are different, but the final output is similar, and the gap in code quality is not very big; but for some basic class libraries When developing methods or methods, we must be cautious and cautious, the code quality must be high, and bugs must be avoided as much as possible.

So how do we produce high-quality code? Unit testing is the correct answer. As the saying goes, 'Anyone who skips unit testing and leaves it to QA testing without careful attention is acting rogue' (I made up this sentence myself); Mocha is a unit testing tool for Javascript. Let’s take a look at how to use it

Concept

Mocha: Javascript testing framework

chai: Assertion library, needs to be used with Mocha

The simplest usage

Step 1: Installation

Assume we are doing unit testing in an existing project

Install Mocha

/*全局安装*/
$ npm  --global mocha  

/*局部安装*/
$ npm install --save-dev mocha

Installing chai

/*局部安装*/
$ npm  --save-dev chai

The difference between global and local: If it is installed locally, the dependencies will be written into the package. json's dependencies or devDependencies, so that when others clone the code from your Github, they don't need to pay attention to 'the dependencies are not complete'? ‘Do I need to install other dependencies? 'Wait for this kind of problem, because 'npm install' will download all dependencies to the local

Step 2: Write Js source file and test file

Source file

     x +   module.exports = add;

Test file

  add = require('./add.js'  expect = require('chai'  describe('加法函数的测试',    it('1 加 1 应该等于 2',      expect(add(1, 1)).to.be.equal(2    it('1 加 -1 应该等于 0',      expect(add(1, -1)).to.be.equal(0  });

Step 3: Run the test file

$ mocha add.test.js

Running screenshot:

The above is the simplest way to use Mocha. It’s very simple, no matter how detailed it is. O(∩_∩)O haha~, below Let’s look at some more advanced ones

Road to Advanced

Advanced One: What are describe and it?

describe: "Test group", also called test block, means that I want to conduct a series of tests, which is equivalent to a group

it: "Test item", also called test case, means that this It is one of the "series of tests", equivalent to item. How to test it? Test logic? They are all implemented in it's callback function

Advanced 2: What? describe also has a "life cycle"?

Each test block (describe) has 4 cycles, which are:

 1 describe('test', function() { 2   // 在本测试块的所有测试用例之前执行且仅执行一次 3   before(function() { 4      5   }); 6   // 在本测试块的所有测试用例之后执行且仅执行一次 7   after(function() { 8      9   });10 11   // 在测试块的每个测试用例之前执行(有几个测试用例it,就执行几次)12   beforeEach(function() {13     14   });15   // 在测试块的每个测试用例之后执行(同上)16   afterEach(function() {17     18   });19   20   // 测试用例21   it('test item1', function () {22 23   })24 });

Advanced three: in the advanced two cycle The code is in ES6 style, and you need to install the babel module for transcoding.

There are two situations here: 1. Global installation 2. Local installation

If babel is installed globally, then we also need to use Global Mocha to call babel-core module

$ npm  -g babel-core babel-preset-es2015
$ mocha --compilers js:babel-core/register

But if babel is installed locally, then we have to use local Mocha to call babel-core module

$ npm install --save-dev babel-core babel-preset-es2015
$ ../node_modules/mocha/bin/mocha --compilers js:babel-core/register

Why? Because Mocha searches for the babel module based on its own path, the global should correspond to the global, and the local should correspond to the local.

There is a very important step missing here: before testing, you need to configure the babel transcoding rules, in the project root Directory, remember 'must be the root directory', create a new .babelrc file, this file is for babel to use

// .babelrc{  "presets": [ "es2015" ] //这里制定使用es2015规则转码}

Advanced 4: Testing can also be Asynchronous?

What is the difference between asynchronous testing and ordinary testing: There is an additional parameter done in the callback function of the test case

 1 var add = require('../src/add.js'); 2 var expect = require('chai').expect; 3  4 describe('加法函数的测试', function() { 5   // 异步测试 6   it('1 加 1 应该等于 2', function(done) { 7     var clock = setTimeout(function () { 8       expect(add(1, 1)).to.be.equal(2); 9       done(); // 通知Mocha测试结束10     },1000);11   });12 13   // 同步测试14   it('1 加 0 应该等于 1', function() {15     expect(add(1, 0)).to.be.equal(1);16   });17 });

Asynchronous testing needs to pay attention to one thing: done must be called manually. Otherwise, the asynchronous test will fail. See the code and running screenshot below:

Code:

 1 var add = require('../src/add.js'); 2 var expect = require('chai').expect; 3  4 describe('加法函数的测试', function() { 5   // 异步测试 6   it('1 加 1 应该等于 2', function(done) { 7     var clock = setTimeout(function () { 8       expect(add(1, 1)).to.be.equal(2); 9       //done();我们不主动调用done,看看会发生什么?10     },1000);11   });12 13   // 同步测试14   it('1 加 0 应该等于 1', function() {15     expect(add(1, 0)).to.be.equal(1);16   });17 });

Running screenshot:

It is not difficult to see from the running results that test case 1 failed, and Mocha reminds us: If it is an asynchronous test or hook, then be sure to ensure that the done method is called, otherwise the test will fail, but it will not affect other Use Case

So, what are the application scenarios of asynchronous testing? That is the test data interface, we can do this:

1 it('异步请求测试', function() {2   return fetch('https://api.github.com')3     .then(function(res) {4       return res.json();5     }).then(function(json) {6       expect(json).to.be.an('object'); // 测试接口返回的是否为对象类型的数据,也就是json格式7     });8 });

Advanced 5: What if we want to only execute a certain test case? Or except for a certain use case, all others are executed

Mocha has two use case management APIs: only and skip

1. If we only want to execute a certain use case, we call it in the only way :

 1 var add = require('../src/add.js'); 2 var expect = require('chai').expect; 3  4 describe('加法函数的测试', function() { 5   // 一个测试组中不是只能有一个only,可以有多个only方式执行的用例 6   it.only('1 加 1 应该等于 2', function() { 7     expect(add(1, 1)).to.be.equal(2); 8   }); 9 10 11   it.only('1 加 0 应该等于 1', function() {12     expect(add(1, 0)).to.be.equal(1);13   });14 15   // 但如果组内已经有了only,那么非only方式执行的用例就一定不会被执行,切记16   it('1 加 -1 应该等于 0', function() {17     expect(add(1, -1)).to.be.equal(0);18   });19 20 });

运行截图:

可以看出,第三个用例并没有被执行

2.如果想跳过某个用例,我们就用skip方式调用它:

 1 var add = require('../src/add.js'); 2 var expect = require('chai').expect; 3  4 describe('加法函数的测试', function() { 5  6   it('1 加 1 应该等于 2', function() { 7     expect(add(1, 1)).to.be.equal(2); 8   }); 9 10   // 同理,skip方式执行的用例在同一组内也可以有多个11   it.skip('1 加 0 应该等于 1', function() {12     expect(add(1, 0)).to.be.equal(1);13   });14 15 16   it.skip('1 加 -1 应该等于 0', function() {17     expect(add(1, -1)).to.be.equal(0);18   });19 20 });

运行截图:

第2,3个用例被跳过了

 

 

结语

以上就是Mocha测试框架的简单介绍,测试api不只有文中的to.be.equal,文中只是"千牛一毛",还有很多api以及更高级的使用特性,详细可参照官方网站:

本文章内容参照了阮一峰老师的文章《测试框架 Mocha 实例教程》,感兴趣的同学可以看一下

The above is the detailed content of Detailed introduction to front-end unit testing framework-Mocha. 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