search
HomeWeb Front-endJS TutorialDetailed explanation of getting started with NodeJS testing framework mocha

This article briefly introduces the installation and simple usage of mocha, the most commonly used testing framework in NodeJS. It supports running Javascript code testing directly on the browser. It is recommended here to everyone

The most commonly used testing framework in NodeJS is probably mocha. It supports a variety of node assert libs, supports both asynchronous and synchronous testing, supports multiple ways to export results, and also supports running Javascript code tests directly on the browser.

Most of the examples in this article are derived from the examples on the official website, and some examples have been modified based on needs or my own feelings. For more introduction, please see the official website: Mocha on Github

Installation:

When you successfully install nodejs v0.10 and npm, execute the following command.

# npm install -g mocha

p.s. For Ubuntu, please note that the nodejs version in the apt source will be older and some module will not be supported. Please install the source code from the nodejs official website.

First step to Mocha:

The following is the simplest mocha example:

var assert = require("assert");
describe('Array', function(){
 describe('#indexOf()', function(){
  it('should return -1 when the value is not present', function(){
     assert.equal(-1, [1,2,3].indexOf(5));
   assert.equal(-1, [1,2,3].indexOf(0));
 })
 })
});

describe (moduleName, testDetails) As can be seen from the above code, describe It can be nested. For example, the two describe nested in the above code can be understood as the tester's desire to test the #indexOf() submodule under the Array module. module_name can be chosen casually, the key is to make it understandable.
it (info, function) The specific test statement will be placed in it's callback function. Generally speaking, infostring will write a brief sentence of the expected correct output. Text description. When the test in the it block fails, the console will print out the detailed information. Generally, the output starts from the module_name of the outermost describe (which can be understood as along the path or recursive chain or callback chain), and finally outputs info, indicating that the expected info content has not been met. An it corresponds to an actual test case
assert.equal (exp1, exp2) assertion to determine whether the result of exp1 is equal to exp2. The equality judgment adopted here is == instead of ===. That is, assert.equal(1, ‘1’) is considered True. This is just an assertion form of assert.js in nodejs. The also commonly used should.js will be mentioned below.
If exp1 and exp2 are both strings, and an error occurs in string comparison, the console will use color to mark the different parts.

Asynchronous

The code in Frist step is obviously Synchronous code, so what should we do with asynchronous code? It's very simple. Add done() to your deepest callback function to indicate the end.

fs = require('fs');
describe('File', function(){
 describe('#readFile()', function(){
   it('should read test.ls without error', function(done){
   fs.readFile('test.ls', function(err){
  if (err) throw err;
  done();
  });
 })
 })
})

done ()
According to waterfall programming habits, the name done means the deepest point of your callback, that is, the end of writing the nested callback function. But for the callback chain, done actually means telling mocha to start testing from here, and call back layer by layer.

The above example code is for test pass. We try to change test.ls to the non-existent test.as. The specific error location will be returned.

There may be a question here. If I have two asynchronous functions (two forked callback chains), where should I add done()? In fact, there should not be two functions to be tested in one it at this time. In fact, done can only be called once in one it. When you call done multiple times, mocha will throw an error. So it should be similar to this:

fs = require('fs');
describe('File', function(){
 describe('#readFile()', function(){
   it('should read test.ls without error', function(done){
   fs.readFile('test.ls', function(err){
  if (err) throw err;
  done();
  });
 })
   it('should read test.js without error', function(done){
   fs.readFile('test.js', function(err){
  if (err) throw err;
  done();
  });
 })
 })
})

Pending

That is, omit the test details and only keep the function body. It is generally applicable to situations such as the person responsible for testing the framework has written the framework and let the team members implement the details, or the test details have not been fully implemented correctly and should be annotated first to avoid affecting the overall test situation. In this case, mocha will default to the test pass.
It works a bit like Python's pass.

describe('Array', function(){
 describe('#indexOf()', function(){
  it('should return -1 when the value is not present', function(){
 })
 })
});

Exclusive && Inclusive

In fact, it is easy to understand, corresponding to the only and skip functions respectively.

fs = require('fs');
describe('File', function(){
 describe('#readFile()', function(){
   it.skip('should read test.ls without error', function(done){
   fs.readFile('test.ls', function(err){
  if (err) throw err;
  done();
  });
 })
   it('should read test.js without error', function(done){
 })
 })
})

The above code will only have one test complete, only the only one will be executed, and the other one will be ignored. There can only be one only in each function. If it.skip, then this case will be ignored.

There is no practical significance in sharing only and skip, because the function of only will block skip.

fs = require('fs');
describe('File', function(){
 describe('#readFile()', function(){
   it.skip('should read test.ls without error', function(done){
   fs.readFile('test.as', function(err){
  if (err) throw err;
  done();
  });
 })
   it('should read test.js without error', function(done){
 })
 })
})

Although test.as does not exist in the above code, test complete will still be displayed due to skip.

Before && After

Before and after are often used in unit tests. mocha also provides beforeEach() and afterEach().
Here is expressed in livescript for the convenience of reading, !-> can be understood as function(){}. There is no need to read the details carefully, just understand how to use these functions through the framework.

require! assert
require! fs
can = it


describe 'Array', !->
 beforeEach !->
 console.log 'beforeEach Array'

 before !->
 console.log 'before Array'
 
 before !->
 console.log 'before Array second time'

 after !->
 console.log 'after Array'

 describe '#indexOf()', !->
 can 'should return -1 when the value is not present', !->
  assert.equal -1, [1,2,3].indexOf 0
 can 'should return 1 when the value is not present', !->

 describe 'File', !->

 beforeEach !->
  console.log 'beforeEach file test!'

 afterEach !->
  console.log 'afterEach File test!'

 describe '#readFile()', !->
  can 'should read test.ls without error', !(done)->
  fs.readFile 'test.ls', !(err)->
   if err
   throw err
   done!
  can 'should read test.js without error', !(done)->
  fs.readFile 'test.js', !(err)->
   if err
   throw err
   done!

It can be seen from the results (the use of after is the same as before),

beforeEach will take effect on all sub-cases under the current describe.
There is no special order requirement for the codes before and after.
There can be multiple befores under the same describe, and the execution order is the same as the code order.
The execution order under the same describe is before, beforeEach, afterEach, after
When an it has multiple befores, the execution order starts from the before of the outermost describe, and the rest are the same.

Test Driven Develop (TDD)

mocha默认的模式是Behavior Driven Develop (BDD),要想执行TDD的test的时候需要加上参数,如

mocha -u tdd test.js

前文所讲的describe, it, before, after等都属于BDD的范畴,对于TDD,我们用suite, test, setup, teardown。样例代码如下:

suite 'Array', !->
 setup !->
 console.log 'setup'

 teardown !->
 console.log 'teardown'

 suite '#indexOf()', !->
 test 'should return -1 when not present', !->
  assert.equal -1, [1,2,3].indexOf 4

The above is the detailed content of Detailed explanation of getting started with NodeJS 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
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.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 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.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

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

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

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.

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),