Created
July 19, 2020 07:13
-
-
Save dgroh/23a014024053f9340791627f32c05b65 to your computer and use it in GitHub Desktop.
Unit testing Express endpoints with Sinon
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
// eslint-disable-next-line | |
const should = require('should') | |
const sinon = require('sinon'); | |
const proxyquire = require('proxyquire'); | |
describe('userRouter', () => { | |
let expressStub; | |
let controllerStub; | |
let RouterStub; | |
let rootRouteStub; | |
let idRouterStub; | |
before(() => { | |
rootRouteStub = { | |
get: sinon.stub().callsFake(() => rootRouteStub), | |
post: sinon.stub().callsFake(() => rootRouteStub), | |
}; | |
idRouterStub = { | |
get: sinon.stub().callsFake(() => idRouterStub), | |
put: sinon.stub().callsFake(() => idRouterStub), | |
delete: sinon.stub().callsFake(() => idRouterStub), | |
}; | |
RouterStub = { | |
route: sinon.stub().callsFake((route) => { | |
if (route === '/:id') { | |
return idRouterStub; | |
} | |
return rootRouteStub; | |
}), | |
}; | |
expressStub = { | |
Router: sinon.stub().returns(RouterStub), | |
}; | |
controllerStub = { | |
getAll: sinon.mock(), | |
getOne: sinon.mock(), | |
}; | |
proxyquire('../routes/userRouter.js', | |
{ | |
express: expressStub, | |
usersController: controllerStub, | |
})({}); | |
}); | |
it('should map /users get router with getAll controller', () => { | |
sinon.assert.calledWith(RouterStub.route, '/users'); | |
sinon.assert.calledWith(rootRouteStub.get, controllerStub.getAll); | |
}); | |
it('should map /users/:id get router with getOne controller', () => { | |
sinon.assert.calledWith(RouterStub.route, '/users/:id'); | |
sinon.assert.calledWith(idRouterStub.get, controllerStub.getOne) | |
}); | |
}); | |
// BASED ON: https://stackoverflow.com/questions/38190712/how-to-unit-test-a-node-api-using-sinon-express-with-mongo-db |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment