search
HomeWeb Front-endJS TutorialA brief introduction to the testing framework Mocha under NodeJs

Introduction and code download

Mocha was released in 2011 and is currently one of the most popular javascript frameworks. In this article we focus on its use on NodeJs.

If you need to download the example code, you can find it by going to the official website. https://mochajs.org/

After downloading the code, install the dependencies:

$ cd DemoOfMocha
$ npm install

The code directory structure is as shown in the figure:

A brief introduction to the testing framework Mocha under NodeJs

You can create a new lib folder and test folder in the root directory according to the code directory structure, then create a new lib folder in the test folder, and then use the npm init command to Generate package.json, you can also download the code and run it first

First test

Now create a new sum.js file in the lib directory

exports.sum =function (a,b) {
 return a+b
}

Next, test this script and create a new test script in the lib folder under the test directory: sum.js

//test/lib/sum.js

var sum = require('../../lib/sum')
var assert = require('assert')

describe('和函数的测试',function () {
 it('1加1应该等于2',function () {
 var expect=10;
 assert.equal(sum(1,1),expect);
 })
})

The above code is a test script. The test script can be executed independently. The test script should contain one or more describe blocks, and each describe block should also contain one or more it blocks

## The #describe block is a "test suite", which represents a group of related tests, which is a function, and the second one is the function that can actually be executed

It block is a "test case" which represents a single test, the test The smallest unit is also a function. The first parameter is the name or description of the test case, and the second parameter is the actual executable function

assert is the assertion package (there are many types of assertion packages, here I use NodeJs to With the assertion package), it is judged whether the execution result of the test code is consistent with the expected result. If it is inconsistent, an error will be thrown. In our test script, sum(1,1), the result should be equal to 2

Here we introduce some functions of Assert's assertion module


assert.fail(actual, expected, message, operator)

Use the specified operator to test whether actual (real value) is equal to expected (expected value) consistent.

assert.ok(value, [message])

Test whether the actual value is true, which has the same effect as assert.equal(true, value, message);

assert.equal(actual, expected, [message])

Use the equality comparison operator (==) to test whether the actual value is shallow, coercive and equal to the expected value.

assert.notEqual(actual, expected, [message])

Use the inequality comparison operator (!=) to test whether the actual value is shallow (shallow), coercive (coercive) and the expected value is not equal.

assert.deepEqual(actual, expected, [message])

Test whether the actual value is deeply equal to the expected value.

assert.notDeepEqual(actual, expected, [message])

Test whether the actual value is deeply unequal to the expected value.

assert.strictEqual(actual, expected, [message])

Use the strict equality operator ( === ) to test whether the actual value is strictly equal to the expected value.

assert.notStrictEqual(actual, expected, [message])

Use the strict inequality operator ( !== ) to test whether the actual value is strictly not equal to the expected value.

assert.throws(block, [error], [message])

Throws an error (error) when a block is expected. The error can be a constructor, a regular expression or other validator.

Next we update the scripts field in package.json


{
 "name": "DemoOfMocha",
 "version": "1.0.0",
 "description": "demo of mocha",
 "main": "index.js",
 "directories": {
 "test": "test"
 },
 "dependencies": {},
 "devDependencies": {},
 "scripts": {
 "test": "NODE_ENV=test mocha test/**/*.js"
 },
 "keywords": [
 "deom",
 "mocha"
 ],
 "author": "wjszxli",
 "license": "ISC"
}

We install MochaJS through the npm command


$ npm install mocha --save-dev

We added the command to run the test, and then use the command to obtain the test report


$ npm test

The test report is as follows:

A brief introduction to the testing framework Mocha under NodeJs

In this way, our first test was successful

Let the test report become more beautiful

We can use the mochawesome module to generate a beautiful report in HTML format, as shown in the figure:

A brief introduction to the testing framework Mocha under NodeJs

Install mochawesome through the following command


$ npm install --save-dev mochawesome

Then update the scripts field in package.json


 "name": "DemoOfMocha",
 "version": "1.0.0",
 "description": "demo of mocha",
 "main": "index.js",
 "directories": {
 "test": "test"
 },
 "dependencies": {},
 "devDependencies": {
 "mocha": "^3.2.0",
 "mochawesome": "^2.0.4"
 },
 "scripts": {
 "test": "NODE_ENV=test mocha test/**/*.js --reporter mochawesome"
 },
 "keywords": [
 "deom",
 "mocha"
 ],
 "author": "wjszxli",
 "license": "ISC”
}

Run the test command , the test report is generated in mochawesome-reports

A brief introduction to the testing framework Mocha under NodeJs

Open the html page with a browser, we will see a beautiful test report

A brief introduction to the testing framework Mocha under NodeJs

异步测试

Mocha默认每个测试用例最多执行2000毫秒,2000毫秒之后没有得到结果,就会报错,如果涉及到异步操作的测试用例,2000毫秒是不够的,这个时候我们需要用 -t 或 —timeout 参数指定超时门槛

我们可以修改在package.json中的scripts字段(我们这里改成3000毫秒)

"scripts": {
 "test": "NODE_ENV=test mocha -t 3000 timeout test/**/*.js --reporter mochawesome”
},

写一个异步测试脚本

//test/lib/timeout.js


var assert = require('assert')

describe('测试应该3000毫秒后结束',function () {
 it('测试应该3000毫秒后结束',function (over) {
 var a=false;
 var b = function () {
  a=true;
  assert.ok(a);
  over();
 };
 setTimeout(b,2500);
 })
})

这个测试用例在执行 it 块的时候传入了一个参数 over,在测试结束的时候 必须显式的调用这个函数,告诉Mocha测试结束了,否则Mocha就会等到超时结束的时候报错。

输入命令运行测试用例

A brief introduction to the testing framework Mocha under NodeJs

我们也可以测试异步请求内部地址或者外部的接口,这里我们请求内部地址为例子:

 在根目录新建:app.js

var express = require('express')
var app = express();

app.get('/api/test',function (req,res) {
 res.send({})
})

var port = process.env.PORT || 3000

if (process.env.NODE_ENV !== 'test') {
 app.listen(port);
 console.log('start from http://www.php.cn/:' + port)
} else {
 module.exports = app;
}

在test目录下的lib文件夹中新建 async.js

//test/lib/async.js

var http = require('http')
var assert = require('assert')
var request = require('superagent');

describe("测试异步请求",function () {
 it("测试异步请求返回一个对象",function (next) {
 request
  .get('http://localhost:3000/api/test')
  .end(function(err, res){
  //expect(res).to.be.an('object');
  console.log(res.body);
  assert.deepEqual(res.body,Object)
  next();
  });
 })
})

测试结果

A brief introduction to the testing framework Mocha under NodeJs

Mocha支持对Promist的测试,允许直接返回Promise,等到他的状态发生变化之后,再执行断言

//test/lib/promise.js

var fetch = require('node-fetch');
var http = require('http')
var assert = require('assert')

describe('Promise 异步测试',function () {
 it('异步Promise返回一个对象',function () {
 return fetch('http://localhost:3000/api/test')
  .then(function(res) {
  return res.json();
  }).then(function(json) {
  console.log(json)
  assert.deepEqual(json,{});
  });
 })
})

执行测试

A brief introduction to the testing framework Mocha under NodeJs

测试的钩子

在 describe 块之中,有四个测试用例的钩子:before()、after()、beforeEach()和afterEach()。它们会在指定时间执行。

describe('hooks', function() { 
 before(function() { 
 // 在当前区块的所有测试用例之前执行 
 }); 
 after(function() { 
 // 在当前区块的所有测试用例之后执行 
 }); 
 beforeEach(function() { 
 // 在当前区块的每个测试用例之前执行 
 }); 
 afterEach(function() { 
 // 在当前区块的每个测试用例之后执行 
 }); 
 //测试用例 
});

在test目录下的lib文件夹中新建 hooks.js

//test/lib/hooks.js
var assert = require('assert')

describe('hook示例', function() {
 var foo = false;

 beforeEach(function() {
 foo = true;
 });

 it('修改foo要成功', function() {
 assert.ok(foo)
 });
});

测试结果

A brief introduction to the testing framework Mocha under NodeJs

测试用例管理

如果项目有很多测试用例,但有的时候只希望运行其中几个,这个时候可以用 only 方法,describe 块和 it 块都允许 only 方法,表示只允许运行带有 only 的测试用例

在test目录下的lib文件夹中新建 only.js

//test/lib/only.js

var sum = require('../../lib/sum')
var assert = require('assert')

describe('和函数的测试',function () {
 it('1加2应该等于3',function () {
 var expect=3;
 assert.equal(sum(1,2),expect);
 })

 it.only('3加4应该等于7',function () {
 var expect=7;
 assert.equal(sum(3,4),expect);
 })
})

测试结果:

A brief introduction to the testing framework Mocha under NodeJs

还有 skip 方法,表示跳过指定的测试用例

在test目录下的lib文件夹中新建 skip.js

//test/lib/only.js

var sum = require('../../lib/sum')
var assert = require('assert')

describe('和函数的测试',function () {
 it('5加6应该等于11',function () {
 var expect=11;
 assert.equal(sum(5,6),expect);
 })

 it.skip('7加8应该等于15',function () {
 var expect=15;
 assert.equal(sum(7,8),expect);
 })
})

测试结果如下,跳过的用 - 号表示

A brief introduction to the testing framework Mocha under NodeJs

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持PHP中文网。

更多A brief introduction to the testing framework Mocha under NodeJs相关文章请关注PHP中文网!


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

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),