TLDW: Testing NodeJS w/ Mocha
6:00: Assertions -comparisons which throw exception upon failure
const assert = value => if ( ! value ) throw new Error ( 'assertion failure!' )
6:54: Unit Test -asserts "unit" behaves as intended, "unit" typically a function
9:00: Integration Test -asserts aggregate of units or modules behave as intended (e.g. side effects done correctly, state changes etc.)
12:00: install as dev dependency
npm i -D mocha
12:22: Obligatory Test Example
module . exports = ( req , res , next ) => {
req . requestTime = Date . now ( ) ; //add request timestamp to req object
next ( ) ; //carry on
}
15:13: Unit Test Example
mkdir test cd test touch request-time.spec.js
16:27: Possble reason = reduces boilerplate for tests
describe ( 'requestTime middleware' , function ( ) {
// Tests go here
} ) ;
18:47: Mocha uses Node.js' assert module
const assert = require ( 'assert' ) ;
const requestTime = require ( '../lib/request-time' ) ; // our middleware
23:54: Create a test with it(title, callback)
describe ( 'requestTime middleware' , function ( ) {
it ( 'should add `requestTIme` property to req param' , function ( ) {
// call function
const req = { } ;
requestTime ( req , null , ( ) => { } ) ;
// make assertions
assert . ok ( req . requestTime > 0 ) ;
} ) ;
} ) ;
26:28: Run the test
$ <app>/mocha
32:29: Tools to use
npm i -D supertest
: Integration tests for express framework
const assert = require ( 'assert' ) ;
const app = require ( '../app' ) ;
const request = require ( 'supertest' ) ;
describe ( 'GET /unix-timestamp' , function ( ) {
it ( 'should respond with JSON obj containing timestamp' , function ( done ) {
//test goes here
} ) ;
} ) ;
it ( 'should respond with JSON obj containing timestamp' , function ( done ) {
request ( app ) . get ( '/unix-timestamp' )
. expect ( 200 ) . end ( ( err , res ) => {
if ( err ) return done ( err ) ;
assert . ok ( res . body . timestamp < 1e10 ) ;
done ( ) ;
} ) ;
Promise Style (Cleaner than Nodeback)
function ( ) {
return request ( app ) . get ( '/unix-timestamp' )
. expect ( 200 )
. then ( res => assert . ok ( res . body . timestamp < 1e10 ) ) ;
}