02.24.2014 — JavaScript, Node.js, Testing

Developing maintainable apps requires having good test coverage. The JavaScript community has created some awesome tools that make it easy to implement workflows for code linting, unit/integration testing, and measuring code coverage. This post focuses on how to develop tests with Mocha and Supertest and how to generate code coverage reports with Istanbul.

Demo App Functionality

I created a simple node.js app to demonstrate testing and code coverage. The source code for this app is on github here: https://github.com/gregjopa/express-app-testing-demo. This app uses Flickr's public feed api to search public photos. It has basic form functionality for entering search terms and based on that form input it retrieves photos. All logic in this app is handled on the server-side and no client-side JavaScript is used. This app is hosted on heroku here: https://express-app-testing-demo.herokuapp.com/.

This app uses the express.js framework along with request and ejs. Grunt is used for implementing workflows for code linting, testing, and code coverage.

Preparing a Test Plan

I recommend designing a test plan at the same time you design your application's functionality. Think about the different components of the app and how they can break. For example, if the app depends on an external api service assume that the api service can go offline or return invalid data. If the app accepts user input assume that the user input can be invalid and possibly dangerous. In my opinion the purpose of the test plan is to be an outline for developers as they write tests. The test plan should not be documentation for the tests since it can easily become out-of-date. Instead, your tests should be self-describing. For example, here is a simple test plan for this photo searching app:

Form input - if the user enters valid search terms the app should work. Form input - if the user enters invalid search terms the app should return an error. API data - if the data returned from the flickr api is valid the app should work. API data - if the data returned from the flickr api is invalid the app should return an error. API data - if the flickr api returns zero results an alert should be returned to notify the user. Route - if the app is working correctly a 200 http status code should be returned. Route - if there is a server error a 500 http status code should be returned.

Tests

There are different types of tests that can be implemented when testing web applications:

Unit tests - isolate a small block of code and test it's intention

Integration tests - test how different components of an application work together

Service tests - isolate a service to see if it's working correctly (ex: api endpoint, database)

My test app includes unit tests, integration tests, and api tests. I'm using the assertion library should.js for clean and readable tests.

Unit Tests

Form validation methods are a good example for unit testing. Typically form validation methods take in a single input parameter and use a regular expression to see the input value is valid or not.

Here's a form validation method with a couple Mocha unit tests:

1 var isValidCommaDelimitedList = function ( value ) { 2 3 var commaDelimitedListRegEx = /^[A-Za-z,\s]+$/ ; 4 return commaDelimitedListRegEx . test ( value ) ; 5 } ; 6 7 8 describe ( 'isValidCommaDelimitedList(value)' , function ( ) { 9 10 it ( 'should return true for valid list of search terms' , function ( ) { 11 var tags = 'california, sunset, red' ; 12 formValidator . isValidCommaDelimitedList ( tags ) . should . be . true ; 13 } ) ; 14 15 it ( 'should return false for search term containing numbers' , function ( ) { 16 var tags = 'dogs123' ; 17 formValidator . isValidCommaDelimitedList ( tags ) . should . be . false ; 18 } ) ; 19 20 } ) ;

Integration Tests for Routes

Node web application routes can be tested using the Supertest library. Supertest can start up a node app, make http requests to routes, and run assertions on http responses. It can pass parameters to routes and run assertions on things like the response http status code, content type, and execute regular expressions against the response body.

If your routes depend on accessing a database or api I recommend mocking that data for your route tests. This way your database or api won't influence your route test results. I'm using the node module nock in my project to mock the data returned by the flickr public feed api.

Here are some route tests:

1 2 app . get ( '/' , function ( req , res ) { 3 var tags = req . param ( 'tags' ) ; 4 var tagmode = req . param ( 'tagmode' ) ; 5 6 } ) ; 7 8 9 describe ( 'index route' , function ( ) { 10 11 it ( 'should respond with a 200 with invalid query parameters' , function ( done ) { 12 13 request ( app ) 14 . get ( '/?tags=california123&tagmode=all' ) 15 . expect ( 'Content-Type' , /html/ ) 16 . expect ( 200 ) 17 . expect ( /<div class="alert alert-danger">/ , done ) ; 18 } ) ; 19 20 it ( 'should respond with a 500 error due to bad jsonp data' , function ( done ) { 21 22 23 var jsonpData = 'jsonFlickrFeed{"items": [' + 24 '{ "title": "Boating",' + 25 '"media": {"m":"http://farm4.staticflickr.com/3727/12608622365_9e9b8b377d_m.jpg"} },' + 26 '{ "title": "Signs",' + 27 '"media": {"m":"http://farm8.staticflickr.com/7446/12608714423_efaf73400c_m.jpg"} }' + 28 ']}' ; 29 30 var flickrFeedApi = nock ( 'http://api.flickr.com' ) 31 . get ( '/services/feeds/photos_public.gne?tags=california&tagmode=all&format=json' ) 32 . reply ( 200 , jsonpData ) ; 33 34 request ( app ) 35 . get ( '/?tags=california&tagmode=all' ) 36 . expect ( 500 , done ) ; 37 38 } ) ; 39 40 } ) ;

API Tests

It can be helpful to have tests for an external service used by your app. If you rely on external services and you have tests for them then when your app breaks it easier to determine if the problem is with your code base or the external service.

Mocha makes it easily to asynchronously test an api endpoint. Here's a test I have for flickr's public feed api:

1 2 function API ( params ) { 3 this . uri = 'http://api.flickr.com/services/feeds/photos_public.gne' ; 4 this . qs = { 5 tags : params . tags || '' , 6 tagmode : params . tagmode || '' , 7 format : params . format || 'json' 8 } ; 9 } 10 11 12 describe ( 'flickr public feed api' , function ( ) { 13 14 it ( 'should return expected json format' , function ( done ) { 15 16 var apiTest = new API ( { 17 tags : 'california' , 18 tagmode : 'all' 19 } ) ; 20 21 request . get ( apiTest , function ( error , response , body ) { 22 response . statusCode . should . equal ( 200 , 'Invalid http status code' ) ; 23 24 var json = jsonpHelper . parseJSONP ( body ) ; 25 json . should . have . property ( 'items' ) ; 26 27 var photos = json . items ; 28 photos . should . be . an . instanceOf ( Array ) ; 29 30 photos . forEach ( function ( photo ) { 31 photo . should . have . keys ( 32 'title' , 33 'link' , 34 'media' , 35 'date_taken' , 36 'description' , 37 'published' , 38 'author' , 39 'author_id' , 40 'tags' 41 ) ; 42 } ) ; 43 44 done ( ) ; 45 } ) ; 46 47 } ) ; 48 49 } ) ;

Code Coverage

Code coverage tools analyze an application's source code and test suite and then identify code that's missing tests. Code coverage provides a way to measure the quality of your application.

Istanbul

Istanbul is a JavaScript code coverage tool that provides instrumentation and reporting. It has an html reporting option and also an lcov reporting option that can be used with the code quality tool SonarQube.

Here's a screenshot of the Istanbul html reporter for a module with zero tests:

After adding tests for all methods in this module the html report will look like this:

Istanbul can be installed as a global node module and used from the command line. Or you can use Istanbul as a local module with Grunt which is the approach I took with my test app. I describe configuring Istanbul with Grunt in the following "Grunt Workflow" section.

SonarQube

SonarQube is a code quality tool that provides code coverage reporting as well as many other features. It's possible to integrate a JavaScript project into Sonar by using Istanbul's instrumentation. Istanbul can output an lcov.info file that can be used by the sonar-runner. The sonar-runner works by reading a config file at the root of your project, performing some analysis, and then uploading statistics to the SonarQube server. Here is a link to my test project's sonar config file: https://github.com/gregjopa/express-app-testing-demo/blob/master/sonar-project.properties

Sonar stores code coverage statistics about your application in a database which makes it possible to compare different versions of your application to see if your code coverage is getting better or worse.

Here's a screenshot of this test project in SonarQube:

Grunt Workflow

Grunt can be used to configure Mocha and Istanbul so you don't need to worry about installing them as global modules. Here are the grunt plugins I'm using for Mocha and Instanbul:

The grunt-istanbul plugin is easy to use with Mocha or any other testing framework. To configure the grunt-istanbul plugin setup a task to run the following:

Instrument your source code Run your test suite against your instrumented source code Store your coverage results Make the report

I follow these steps in my test project's Gruntfile here: https://github.com/gregjopa/express-app-testing-demo/blob/master/Gruntfile.js

When I normally run my test suite I want it to point directly at my source code. But when I run the Istanbul code coverage task I want my test suite to point at the instrumented source code. To accomplish this I created a require_helper module. This require_helper module uses an environment variable to determine which path to use for loading the source code to run the tests against. When I execute my code coverage grunt task I set the environment variable using the grunt-env plugin to point to the instrumented source code. Here's some example code to demonstrate how this requireHelper module works:

1 2 module . exports = function ( path ) { 3 return require ( ( process . env . APP_DIR_FOR_CODE_COVERAGE || '../app/' ) + path ) ; 4 } ; 5 6 7 var requireHelper = require ( '../require_helper' ) ; 8 var formValidator = requireHelper ( 'form_validator' ) ;

Conclusion

Code coverage is easy to setup using Grunt and Istanbul. Having statistics like code coverage will make your application easier to maintain and update. But code coverage is not perfect so make sure to still manually review your source code to see if you have tests for every use case. For my next post I plan on writing about testing and code coverage for client-side JavaScript apps.