Skip to content

Instantly share code, notes, and snippets.

@sakovias
Created January 19, 2016 16:30
Show Gist options
  • Save sakovias/5b878cd9866b85afe4e3 to your computer and use it in GitHub Desktop.
Save sakovias/5b878cd9866b85afe4e3 to your computer and use it in GitHub Desktop.
Stubbing module functions in a node server for unit testing edge cases
var lib = function() {};
lib.prototype.sayHi = function() {
return 'Hello from the original module';
};
module.exports = lib;
{
"dependencies": {
"express": "*",
"sinon": "*",
"supertest-as-promised": "*",
"should": "*",
}
}
var Lib = require('./lib');
var app = require('express')();
var server = {};
var runningInstance;
app.get('/hello', function(req, res) {
var lib = new Lib();
res.json(lib.sayHi());
});
server.start = function(cb) {
runningInstance = app.listen(7777, cb);
};
server.close = function(cb) {
if(!runningInstance) return cb(null);
runningInstance.close(cb);
};
module.exports = server;
require('should');
var request = require('supertest-as-promised');
var sinon = require('sinon');
var server = require('./server');
var Lib = require('./lib') ;
before(function(done) {
server.start(done);
});
after(function(done) {
server.close(done);
});
it('Replies on GET /hello', function(done) {
request('localhost:7777')
.get('/hello')
.expect(200)
.then(function(res) {
res.body.should.containEql('Hello from the original module');
done();
}).catch(done);
});
it('Can be mocked', function(done) {
sinon.stub(Lib.prototype, 'sayHi', function() {
return 'Hello from the stub!';
});
request('localhost:7777')
.get('/hello')
.expect(200)
.then(function(res) {
res.body.should.containEql('Hello from the stub!');
Lib.prototype.sayHi.restore();
done();
}).catch(done);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment