Introduction to NodeJS testing framework mocha

Source: Internet
Author: User
This article briefly introduces the mocha installation and simple usage of the most common testing framework in NodeJS, and supports Javascript code testing directly on the browser, this article briefly introduces the most common testing framework in NodeJS-mocha installation and simple usage. It supports Javascript code testing directly on the browser, here we recommend you

The most common testing framework in NodeJS is mocha. It supports assert libs of multiple nodes, asynchronous and synchronous testing, multiple export methods, and Javascript code testing on browser.

Most of the examples in this article are from the official website. Some examples are modified based on your needs or your own feelings. For more information, see the official website Mocha on Github.

Installation:

After nodejs v0.10 and npm are successfully installed, run the following command.

# npm install -g mocha

P.s. Ubuntu note that the node. js version in the apt source will be old, and some modules will not support it. Please install the source code from the node. js 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) can be seen from the above Code that describe can be nested, for example, the two describe nested in the above Code can be understood as the # indexOf () submodule under the Array module that the tester wants to test. Module_name can be obtained at will. The key is to make people understand it.
The specific test Statement of it (info, function) will be placed in the it callback function. Generally, the info string will write a brief text description of the expected correct output. When the test failed in the it block is displayed, the console prints the detailed information. Generally, the output starts from the le_name of describe in the outermost layer (which can be understood as a path, recursive chain, or callback chain), and finally outputs info, indicating that the expected info content is not met. One it corresponds to one actual test case
Assert. equal (exp1, exp2) Assertions determine whether the exp1 result is equal to exp2. Here the equals judgment is = rather than =. That is, assert. equal (1, '1') is considered to be True. This is just an assert. js assert form in nodejs, which is also commonly used in the following sections.
If both exp1 and exp2 are strings, when an error occurs in character string comparison, the console uses different colors to mark different parts.

Asynchronous

The code in Frist step is obviously a Synchronous Code. So what should I do with asynchronous code? Simply put, add done () in 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 the waterfall stream programming habits, the name "done" indicates the deepest part of your callback, that is, to end writing nested callback functions. However, for the callback chain, done actually tells mocha to start testing and calls back each layer.

The code in the above example is test pass. We try to change test. ls to a non-existent test.. The specific error location is returned.

There may be a question: Where should I add done () if I have two asynchronous functions (two forked callback chains? In fact, there should not be two functions to be tested in one it. In fact, only one done can be called in one it. When you call done multiple times, mocha will throw an error. So it should be like 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, save the Test details and only retain the function body. General Applicability: for example, write a framework for testing the framework to allow the team members to implement the details, or comment out the test details before they are fully implemented to avoid affecting the global test. In this case, mocha will default the test pass.
It works a bit like Python pass.

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

Exclusive

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 only has one test complete. only the test complete will be executed, and the other will be ignored. Each function can only have one only. This case will be ignored if it. skip is used.

Only and skip sharing have no practical significance, because the only function will block the 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){ }) })})

The code above, although test. as does not exist, still displays test complete due to skip.

Before & After

Before and after are often used in unit tests. Mocha also provides beforeEach () and afterEach ().
Livescript is used for easy reading ,! -> Function (){}. You do not need to read the details carefully. You only need to know how to use these functions through the framework.

require! assertrequire! fscan = itdescribe '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!

The results show that (the use of after is the same as that of before ),

BeforeEach takes effect for all subcases in the current describe.
Before and after codes have no special order requirements.
There can be multiple before under the same describe, and the execution sequence is the same as the code sequence.
The execution sequence of the same describe is before, beforeEach, afterEach, after
When one it has multiple before, the execution sequence starts from the before of the describe, and the rest is the same.

Test Driven Develop (TDD)

The default mocha mode is Behavior Driven Develop (BDD). To execute TDD test, you must add parameters, such

mocha -u tdd test.js

The describe, it, before, and after mentioned above all belong to the scope of BDD. For TDD, we use suite, test, setup, and teardown. The sample code is as follows:

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 a detailed description of the node. js testing framework mocha entry. For more information, see other related articles in the first PHP community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.