Test coverage for [node. js] Express

Source: Internet
Author: User

Original address: http://www.moye.me/2014/12/03/express_coverage/

Introduction

A group of friends asked the express how to do unit Test/coverage test, which is omitted from the previous article, hereby fill in

Express Web Test

The first thing to do in the Express Web test is which side to test:

    • Client Request response test is black box, requires pre-boot site, and cannot attach coverage test
    • Unit tests on the server require Mock, additional coverage testing

We need to do coverage testing for express routing, and obviously we will choose to do the testing on the server side. This means: The Express application that each case needs to access is not pre-initiated:

var express = require (' Express '); var app = Express (); // Some router code ... App.listen (3000);

We need a tool to create a startup Express application and Mock requests for it, so that the test framework can detect the path and coverage of the routing method's internal code execution.

Here, we introduce SuperTest as a mock tool.

SuperTest

SuperTest is another piece of TJ's great God: Based on superagent, provides a high level of abstraction for HTTP testing. The so-called highly abstract meaning is: can embed various kinds of test framework, provide the semantic good assertion.

See section SuperTest Combined with Mocha code:

 var  app = require ('.. /app '  var  request = require (' SuperTest ' );d Escribe (  ' Router testing ',  () {It (  ' site root response ', function   (done) {R Equest (APP). Get ( '/'  ' content-type ', ' text/html ; Charset=utf-8 '  200). End  ( function   (err, res) { if  (Err) throw   err;            Done ();    }); });

Easy to understand, the point is that it drives Express.

Test coverage

Code coverage is a measure of a software test that describes the scale and extent of the source code being tested in the program, and the resulting scale is called code coverage.

Here are a few coverage metrics:

    • Function coverage: Call every function in the program?
    • Line coverage: Did you execute every line in the program?
    • Statement coverage (Statement coverage): If you are using a control flow graph to represent a program, execute it to each node in the control flow graph?
    • Branch coverage (Branches coverage): If you are using a control flow graph to represent a program, do you want to perform each edge in the control flow graph? For example, does all the if directives in the control structure have a situation in which logical expressions are executed and not established?
    • Conditional coverage (Condition coverage): Also known as predicate override (predicate coverage), is there a case in which each of the conditions in each logical expression (a logical expression that cannot be decomposed) is executed and not established?

The preference for indicators can be said to be a matter of opinion, such as the famous Coveralls.io on the line coverage (lines coverage) as the first choice for the project to issue badge.

What we need is a tool that can draw coverage metrics based on test cases:

Istanbul

Istanbul is such a tool, can produce statements/lines/functions/branches and other indicator reports, and exported in various formats.

It is commendable that Istanbul can be well integrated with Mocha, such as: to place test cases uniformly under/test, to test them and generate coverage reports, you can add such a configuration in Package.json:

"Scripts": {    "test": "Mocha--recursive--timeout 500000 test/--bail",    "Test-cov": "Node Node_modules/istanbul-harmony/lib/cli.js cover./node_modules/mocha/bin/_mocha  ----Timeout 500000--recursive test/--bail "}

Use commands in the project directory only when testing is required:

NPM Test

When you need to test and append coverage reports, use commands in the project directory:

NPM Run-script Test-cov

After the test section is complete, you will get the following report information (in the Project/coverage directory, lcov.info and other coverage data files are generated:

Instance

Mock tools are available, test frameworks and coverage tools are also available, and the actual combat is poor. Here's a chestnut to see how to do Express coverage testing:

  1. Global installation Mocha, Istanbul and Express
    Install -G mocha
    Install -G Istanbul
    Install -G Express
  2. Generate an Express site:
    Express-e Express-coverage
  3. Modify the Package.json as follows and usenpm install 安装需要的包:
    {  "Name": "Express-coverage",  "Version": "0.0.1",  "Scripts": {    "Test": "Mocha test/--bail",    "Test-cov": "Node Node_modules/istanbul-harmony/lib/cli.js cover./node_modules/mocha/bin/_mocha-test/"  },  "Dependencies": {    "Express": "~4.9.0",    "Body-parser": "~1.8.1",    "Cookie-parser": "~1.3.3",    "Morgan": "~1.3.0",    "Serve-favicon": "~2.1.3",    "Debug": "~2.0.0",    "Ejs": "~0.8.5",    "Istanbul-harmony": "*",    "Should": "*",    "Mocha": "*",    "Mocha-lcov-reporter": "*",    "SuperTest": "*"  }}
  4. Remove the Routes/index.js, bin/www, or routes/users.js:
    var express = require (' Express '); var router = Express. Router (); Router.get (function  (req, res) {    var msg = ' no user ';    Res.send (msg);}); Router.get (function  (req, res) {    var msg = ' User: ' + req.params.id;< c17/>= router;
  5. Create a new test directory under the project, place a router.js, and write the use case:
    varshould = require (' should '));varApp = require ('.. /app ');varRequest = require (' SuperTest ');d Escribe (' Router testing ',function() {It (' Users have a not ID response ',function(done) {request (APP). Get ('/users '). Expect (' Content-type ', ' text/html; Charset=utf-8 '). Expect (200). End (function(Err, res) {if(ERR)Throwerr;                Should.exist (Res.text);            Done ();    });    }); It (' Users have ID response ',function(done) {request (APP). Get ('/users/1/'). Expect (' Content-type ', ' text/html; Charset=utf-8 '). Expect (200). End (function(Err, res) {if(ERR)Throwerr;                Should.exists (Res.text);            Done ();    }); });});
  6. The input command npm run-script test-co gets the coverage report:
  7. the indicator is a bit low, because there are branches and code in the app that are not running: 404 and 500 processing code (these are the generated code for Express-generator:
     app.use ( function   (req, res, next) { var  err = new  Error (' Not Found ' );    Err.status  = 404; Next (err);});    App.use ( function   (err, req, res, next) { Res.status (Err.status  | |    500); Res.render ( ' error '  
  8. In Router.js's original scenario, add a use case, plus a trigger on 404 lines of code:
    function (done) {    request (APP).        get ('/non/')        . Expect (404)        . End (function  (Err, res) {            ifthrow  err;            Done ();        } );
  9. Re-enter npm run-script test-co the command to see the coverage report, we can see the progress:)
Postscript

Finding the right mock tool and test framework and integrating it, web testing and coverage reporting is probably the way to get the idea. On the test framework of various parameter combinations and pattern play, there are many interesting features (such as TRAVIS-CI, Coveralls.io and other public services integration, in the Warehouse Display project status badge ), this article no longer repeat, interested in adding node Learning Exchange Group to explore together.

More articles please visit my blog new address: http://www.moye.me/

Test coverage for [node. js] Express

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.