I'm trying to test the behavior of a particular route. It continues to run the middleware even when I create a stub. I want the event authentication to simply pass for now. I understand that it's not truly a "unit" test at this point. I'm getting there. I've also simplified the code a little. Here is the code to test:
const { rejectUnauthenticated } = require('../modules/event-authentication.middleware');
router.get('/event', rejectUnauthenticated, (req, res) => {
res.sendStatus(200);
});
Here is the middleware I am trying to skip:
const rejectUnauthenticated = async (req, res, next) => {
const { secretKey } = req.query;
if (secretKey) {
next();
} else {
res.status(403).send('Forbidden. Must include Secret Key for Event.');
}
};
module.exports = {
rejectUnauthenticated,
};
The test file:
const chai = require('chai');
const chaiHttp = require('chai-http');
const sinon = require('sinon');
let app;
const authenticationMiddleware = require('../server/modules/event-authentication.middleware');
const { expect } = chai;
chai.use(chaiHttp);
describe('with correct secret key', () => {
it('should return bracket', (done) => {
sinon.stub(authenticationMiddleware, 'rejectUnauthenticated')
.callsFake(async (req, res, next) => next());
app = require('../server/server.js');
chai.request(app)
.get('/code-championship/registrant/event')
.end((err, response) => {
expect(response).to.have.status(200);
authenticationMiddleware.rejectUnauthenticated.restore();
done();
});
});
});
I've tried following other similar questions like this: How to mock middleware in Express to skip authentication for unit test? and this: node express es6 sinon stubbing middleware not working but I'm still getting the 403 from the middleware that should be skipped. I also ran the tests in debug mode, so I know the middleware function that should be stubbed is still running.
Is this an issue with stubbing my code? Is this an ES6 issue?
Can I restructure my code or the test to make this work?