Detailed introduction to front-end unit testing framework-Mocha
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Evaluating the cost/performance of commercial support for a Java framework involves the following steps: Determine the required level of assurance and service level agreement (SLA) guarantees. The experience and expertise of the research support team. Consider additional services such as upgrades, troubleshooting, and performance optimization. Weigh business support costs against risk mitigation and increased efficiency.

The learning curve of a PHP framework depends on language proficiency, framework complexity, documentation quality, and community support. The learning curve of PHP frameworks is higher when compared to Python frameworks and lower when compared to Ruby frameworks. Compared to Java frameworks, PHP frameworks have a moderate learning curve but a shorter time to get started.

The lightweight PHP framework improves application performance through small size and low resource consumption. Its features include: small size, fast startup, low memory usage, improved response speed and throughput, and reduced resource consumption. Practical case: SlimFramework creates REST API, only 500KB, high responsiveness and high throughput

Choose the best Go framework based on application scenarios: consider application type, language features, performance requirements, and ecosystem. Common Go frameworks: Gin (Web application), Echo (Web service), Fiber (high throughput), gorm (ORM), fasthttp (speed). Practical case: building REST API (Fiber) and interacting with the database (gorm). Choose a framework: choose fasthttp for key performance, Gin/Echo for flexible web applications, and gorm for database interaction.

React's main functions include componentized thinking, state management and virtual DOM. 1) The idea of componentization allows splitting the UI into reusable parts to improve code readability and maintainability. 2) State management manages dynamic data through state and props, and changes trigger UI updates. 3) Virtual DOM optimization performance, update the UI through the calculation of the minimum operation of DOM replica in memory.

Java framework learning roadmap for different fields: Web development: SpringBoot and PlayFramework. Persistence layer: Hibernate and JPA. Server-side reactive programming: ReactorCore and SpringWebFlux. Real-time computing: ApacheStorm and ApacheSpark. Cloud Computing: AWS SDK for Java and Google Cloud Java.

A few days ago, Google officially pushed the Android 15 Beta 4 update to eligible Pixel smartphone and tablet users. This marks that the Android 15 operating system has entered the platform stable stage, indicating that its stable version will be officially released with global users in the next few days. Meet. At the same time, this development also injects new vitality into Samsung Electronics' Galaxy device series to accelerate the development process of its OneUI7.0 version. 1.[Android15Beta4 promotes Samsung OneUI7.0 stable build](https://www.cnbeta.com/articles/tech/1427022.htm) With Android15Bet

There are five misunderstandings in Go framework learning: over-reliance on the framework and limited flexibility. If you don’t follow the framework conventions, the code will be difficult to maintain. Using outdated libraries can cause security and compatibility issues. Excessive use of packages obfuscates code structure. Ignoring error handling leads to unexpected behavior and crashes.
