Reputation: 91
I'm trying to use Sinon to stub out some custom middleware in an express route but it's not working as I expect it to. I expect it to not log "I am authenticating..." and instead log "Stubbed" to the console. It looks like sinon is not stubbing out the middleware correctly.
test/test.js
const chai = require('chai');
const chaiHttp = require('chai-http');
const sinon = require('sinon');
chai.use(chaiHttp);
const should = chai.should();
const auth = require('../auth');
const app = require('../app')
describe('My routes', function() {
let checkTokenStub;
beforeEach(()=>{
checkTokenStub = sinon.stub(auth,'checkToken').callsFake(()=>{
console.log('Stubbed');
});;
})
it('returns hello', function(done) {
chai.request(app)
.get('/')
.set('X-Auth-Token', 'xyz123')
.end((err,res)=>{
res.text.should.be.eql('Hello')
done(err)
})
});
});
app.js
var express = require('express'),
app = express();
var router = express.Router();
app.use('/', require('./router'));
module.exports = app;
auth.js
exports.checkToken = function(req, res, next) {
console.log('I am authenticating...')
var authToken = req.get('x-auth-token');
if (!authToken)
return res.sendStatus(401);
next();
}
router.js
var express = require('express'),
router = express.Router();
auth = require('./auth');
router.get('/', auth.checkToken, function(req, res, next) {
return res.send('Hello');
});
module.exports = router;
package.json
{
"name": "sinontest",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "mocha --watch"
},
"author": "",
"license": "ISC",
"devDependencies": {
"chai": "^4.1.2",
"chai-http": "^3.0.0",
"mocha": "^4.0.1",
"sinon": "^4.1.1"
},
"dependencies": {
"express": "^4.16.4"
}
}
Upvotes: 6
Views: 2823
Reputation: 91
@Gonzalo.- answered this question in the comments. I had to move the requiring of app to after the stub.
test.js
const chai = require('chai');
const chaiHttp = require('chai-http');
const sinon = require('sinon');
chai.use(chaiHttp);
const should = chai.should();
const auth = require('../auth');
let app;
describe('My routes', function() {
let checkTokenStub;
before(()=>{
checkTokenStub = sinon.stub(auth,'checkToken').callsFake((req,res,next)=>{
console.log('Stubbed');
next()
});
app = require('../app')
})
it('returns hello', function(done) {
chai.request(app)
.get('/')
.set('X-Auth-Token', 'xyz123')
.end((err,res)=>{
res.text.should.be.eql('Hello')
done(err)
})
});
});
Upvotes: 3