Created
January 19, 2016 16:30
-
-
Save sakovias/5b878cd9866b85afe4e3 to your computer and use it in GitHub Desktop.
Stubbing module functions in a node server for unit testing edge cases
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var lib = function() {}; | |
lib.prototype.sayHi = function() { | |
return 'Hello from the original module'; | |
}; | |
module.exports = lib; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"dependencies": { | |
"express": "*", | |
"sinon": "*", | |
"supertest-as-promised": "*", | |
"should": "*", | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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