This article mainly studies:
- Test framework Mocha;
- Assertion Library: should;
- Test rate Coverage Tool Istanbul;
Create and enter Lesson3:
mkdir Lesson3 && Lesson3
Create a main.js and write a test function:
varFibonacci =function(n) {if(typeofN!== ' number '){ Throw NewError (' n should be a number ') } if(N < 0){ Throw NewError (' n should >= 0 ') } if(N > 10){ Throw NewError (' N should <= 10 ') } if(n = = 0){ return0 } if(n = = 1){ return1 } returnFibonacci (n-1) + Fibonacci (n-2)}if(Require.main = = =module) { varn = number (process.argv[2]) Console.log (' Fibonacci (' + n + ') is ', Fibonacci (n))} Exports.fibonacci= Fibonacci
Lesson3 Create the Test folder and create the Main.test.js:
mkdir Test && CD test && echo.>main.test.js
Write test cases in Main.test.js:
varMain = require ('.. /main ')varshould = require (' should ')) describe (' Test/main.test.js ',function() {It (' Should equal 0 when n = = = 0 ',function() {Main.fibonacci (0). should.equal (0)}) it (' Should equal 1 when n = = = 1 ',function() {Main.fibonacci (1). should.equal (1)}) it (' should equal when n = = = 10 ',function() {Main.fibonacci (). Should.equal (55)}) it (' Should throw when n > 10 ',function (){ (function() {Main.fibonacci (11)}). should.Throw(' N should <= 10 ')}) it (' Should throw when n < 0 ',function(){ (function() {Main.fibonacci (-1)}). should.Throw(' N should >= 0 ')}) it (' Should throw when n isnt number ',function(){ (function() {Main.fibonacci (' Tease ')}). should.Throw(' n should be a number ') })})
CMD output:
Mocha
Complete the test as shown:
Install a Istanbul:
CNPM I Istanbul-g
Perform:
Istanbul cover _mocha
(Note: If the window does not find the _mocha file error, find the location of your computer in the Mocha installation directory of the _mocha file replacement _mocha, for example: Istanbul cover c:\users\[user name]\appdata\roaming \npm\node_modules\mocha\bin\_mocha)
As you can see, the branch coverage is 91.67% and the line coverage is 87.5%.
The--node.js of the front end to crawl and Roll (ii)