javascript - Unit testing expressjs application -


i have following module i'm working on adding unit tests for. want ensure app.use called / , appropriate handler this.express.static('www/html'), want ensure app.listen called correct port.

function webservice(express, logger) {     this.express = express;     this.log = logger;     this.port = 3000; }  // init routes , start server webservice.prototype.start = function start() {         var app = this.express();      // setup routes     app.use('/', this.express.static('www/html'));      // startup server     app.listen(this.port);      this.log.info('starting webserver on port %s', this.port);  };  module.exports = webservice; 

if remove app.use (replace simple app.get) can listen tested passing constructor in unit test

var express_stub = function() {                 var tmpobj = {                     get: function() {},                     listen: listen_stub // sinonjs stub                 };                 return tmpobj;             }; 

when switch on using this.express.static in route, falls on (expectedly because this.express doesn't define static) can't quite head wrapped around correct way deal this. this.express() constructor throwing me. can't figure out correct way mock calls want validate in express.

you can use supertest

var request = require('supertest')   , express = require('express');  var app = express();  app.get('/user', function(req, res){   res.send(200, { name: 'tobi' }); });  request(app)   .get('/user')   .expect('content-type', /json/)   .expect('content-length', '20')   .expect(200)   .end(function(err, res){ if (err) throw err;   }); 

using mocha:

describe('get /users', function(){   it('respond json', function(done){     request(app)       .get('/user')       .set('accept', 'application/json')       .expect('content-type', /json/)       .expect(200, done);   }) }) 

i suggest divide 2 file app: app.js contains app code , return module.exports, , server.js file requires app.js , pass new http server listen method. way can write tests doing require of app.js.

this how default app created express generator work.


Comments

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -