Detailed explanation of getting started with NodeJS testing framework mocha

黄舟
Release: 2017-03-28 14:21:30
Original
1583 people have browsed it

This article briefly introduces the installation and simple usage of mocha, the most commonly used testing framework in NodeJS. It supports runningJavascriptcode 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
Copy after login

p.s. For Ubuntu, please note that the nodejs version in the apt source will be older and somemodulewill 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)); }) }) });
Copy after login

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'scallback function. Generally speaking, infostringwill 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(); }); }) }) })
Copy after login

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(); }); }) }) })
Copy after login

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(){ }) }) });
Copy after login

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){ }) }) })
Copy after login

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){ }) }) })
Copy after login

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!
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!