I'm using mocha, chai, and sinon to test some authenticated API routes. I'm using passport.authenticate() as middleware to authenticate the route:
const router = require('express').Router();
const passport = require('passport');
router.post('/route',
passport.authenticate('jwt', {session:false}),
function(req,res) {
return res.status(200);
});
module.exports = router;
Then, in my test suite, I am using sinon to stub out passport.authenticate calls:
const chai = require('chai');
const chaiHttp = require('chai-http');
const sinon = require('sinon');
const passport = require('passport');
const server = require('../../app');
const expect = chai.expect;
chai.use(chaiHttp);
describe('route', function() {
before(function(done) {
sinon.stub(passport, 'authenticate').callsFake(function(test, args) {
console.log('Auth stub');
});
console.log('stub registered');
passport.authenticate('jwt', {session:false});
done();
});
after(function(done) {
console.log('after hook');
passport.authenticate.restore();
done();
});
describe('POST /route', function() {
it('should post', function(done) {
console.log('starting test');
chai.request(server)
.post('/route')
.end(function(err,res) {
expect(res).to.have.status(200);
done();
});
});
});
});
Now, when I run the test suite, I see it print out the following:
route
stub registered
Auth stub
POST /route
starting test
1) should post
after hook
1 failing
1) route
POST /route
should post:
Uncaught AssertionError: expected { Object (_events, _eventsCount, ...) } to have status code 200 but got 401
From this, we can see that the after the stub is registered, I can call it in the test file and it is properly stubbed. But when passport.authenticate() is called in route.post(), it is the actual passport.authenticate() and sends a response with status 401 because I'm not authenticated.
Any thoughts on what's going on?
Your code calls passport.authenticate as soon as it runs, and it runs as soon as it is required.
Because you are requiring the code at the beginning of the test before the stub has been created your code ends up calling the real passport.authenticate.
In order for code like this to call the stub you must set up your stub before you require your code:
const chai = require('chai');
const chaiHttp = require('chai-http');
const sinon = require('sinon');
const passport = require('passport');
// const server = require('../../app'); <= don't require your code here...
const expect = chai.expect;
chai.use(chaiHttp);
describe('route', function () {
before(function (done) {
sinon.stub(passport, 'authenticate').callsFake(function (test, args) {
console.log('Auth stub');
});
console.log('stub registered');
passport.authenticate('jwt', { session: false });
done();
});
after(function (done) {
console.log('after hook');
passport.authenticate.restore();
done();
});
describe('POST /route', function () {
it('should post', function (done) {
console.log('starting test');
const server = require('../../app'); // <= require it AFTER creating the stub
chai.request(server)
.post('/route')
.end(function (err, res) {
expect(res).to.have.status(200);
done();
});
});
});
});
One small note related to sinon stubbing, I manage to have it working using this syntax:
passport.authenticate = sinon.stub( passport, 'authenticate' )
.returns(
( req, res, next ) => {
const user = {
username: 'test user',
email: 'testuser#mail.com',
displayName: 'Test User',
provider: 'testCase',
roles: [ 'admin' ]
}
req.user = user;
next()
}
);
Main things are:
add user data into req.user
execute next() for code flow to continue into next middleware
To recap this is not a way to actually test your authentication strategy but to bypass it in case you want to test router results.
Related
I was trying to get a basic hang of writing the test cases using mocha and chai-http ,I had written the test case as below
let chai = require('chai');
let chaiHttp = require('chai-http');
const should = chai.should;
const expect = chai.expect;
const server = "http://127.0.0.1:3000"
chai.use(chaiHttp);
describe('Create Login and Register', () => {
it('should login using credentials', (done) => {
chai.request(server)
.get('/register')
.send()
.then((res: any) => {
res.should.have.status(200);
done();
}).catch((err: any) => { done(err) })
})
})
and the service that i'm trying to test is as below
const express = require('express');
const app = express();
app.get('/register', function (req, res) {
res.json({
'state': true,
'msg': 'Register endpoint',
'data': {
'username': 'Swarup',
'email': 'abc#gmail.com',
'password': 'P#1234',
'fullName': 'Swarup Default'
}
});
});
app.listen(3000, () => { console.log('started') })
module.exports = app;
but when i run the test case i get an error as given below
1 failing
1) Create Login and Register
should login using credentials:
Error: connect ECONNREFUSED 127.0.0.1:3000
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16)
what is that i'm missing or doing wrong ?
You did not start the HTTP server. You should start the HTTP server in the before hook and teardown it in the after hook.
Besides, you can have your module NOT execute the code in the conditional block at requiring by using require.main === module condition. Because we will require('./app') in our test file, we don't want to start the HTTP server at requiring.
E.g.
app.js:
const express = require('express');
const app = express();
app.get('/register', function (req, res) {
res.json({
state: true,
msg: 'Register endpoint',
data: {
username: 'Swarup',
email: 'abc#gmail.com',
password: 'P#1234',
fullName: 'Swarup Default',
},
});
});
if (require.main === module) {
app.listen(3000, () => {
console.log('started');
});
}
module.exports = app;
app.test.js:
let chai = require('chai');
let chaiHttp = require('chai-http');
let app = require('./app');
const expect = chai.expect;
const endpoint = 'http://127.0.0.1:3000';
chai.use(chaiHttp);
describe('Create Login and Register', () => {
let server;
before(() => {
server = app.listen(3000, () => {
console.log('started for testing');
});
});
after(() => {
server.close();
});
it('should login using credentials', (done) => {
chai
.request(endpoint)
.get('/register')
.send()
.then((res) => {
expect(res).to.have.status(200);
done();
})
.catch((err) => {
done(err);
});
});
});
test result:
Create Login and Register
started for testing
✓ should login using credentials
1 passing (18ms)
I'm trying to stub auth.session when testing endpoint /allowUser2 on an express server app.js.
//--auth.js--
module.exports.session = (req, res, next) => {
req.user = null;
next();
};
//--app.js--
const express = require('express');
const auth = require('./auth');
const app = express();
app.use(auth.session);
app.get('/allowUser2', (req, res) => {
if (!req.user) return res.status(401).send();
if (req.user.user === 2) return res.status(200).send();
});
app.listen(4001).on('listening', () => {
console.log(`HTTP server listening on port 4001`);
});
module.exports = app;
If I just have this one test file test1.js in my test suite, auth gets stubbed successfully.
//--test1.js--
let app;
const sinon = require('sinon');
const auth = require('../../auth.js');
const chai = require('chai');
const chaiHttp = require('chai-http');
const { expect } = chai;
chai.use(chaiHttp);
let agent;
describe('should allow access', () => {
before(async () => {
// delete require.cache[require.resolve('../../app.js')]; // causes Error: listen EADDRINUSE: address already in use
sinon.stub(auth, 'session').callsFake((req, res, next) => {
req.user = { user: 1 };
next();
});
app = require('../../app.js');
agent = chai.request.agent(app);
});
after(async () => {
auth.session.restore();
});
it('should not allow access', async function () {
const response = await agent.get('/allowUser2');
expect(response.status).to.be.equal(200);
});
});
However, if I have more than one test file that requires app.js then I have a problem. If app.js was already required in another test file, such as test2.js below, node doesn't reload app.js when it's required again in test1.js. This causes app.js to call the old auth.session function, not the new stubbed one. So the user isn't authenticated and the test fails.
//--test2.js--
const chai = require('chai');
const chaiHttp = require('chai-http');
const app = require('../../app.js');
const { expect } = chai;
chai.use(chaiHttp);
const agent = chai.request.agent(app);
describe('route /allowUser2', () => {
it("shouldn't allow access", async function () {
const response = await agent.get('/allowUser2');
expect(response.status).to.be.equal(401);
});
});
I tried to reload the app.js by using delete require.cache[require.resolve('../../app.js')];. This worked when reloading a file with a plain function, but when the file is a server like app.js this causes an error: Error: listen EADDRINUSE: address already in use.
Recreate:
download Repo
npm i
npm test
How do you stub a function on the server?
One solution is turn app.js into a function that starts the server on a port number passed in as an argument. Then change the port randomly when requiring. I do not like this option because there may be some reason to keep the app on a specific port.
app.js
const express = require('express');
const auth = require('./auth');
module.exports = (port) => {
const app = express();
app.use(auth.session);
app.get('/allowUser2', (req, res) => {
if (!req.user) return res.status(401).send();
if (req.user.user === 2) return res.status(200).send();
});
app.listen(port).on('listening', () => {
console.log(`HTTP server listening on port ${port}`);
});
return app;
};
when requiring
app = require('../../app.js')((Math.random() * 10000).toString().slice(0, 4));
Instead of exporting the app in app.js, I export a function that launches the server and returns the server instance and app. By exporting the server instance I have the ability to close the server. The app is needed to pass into chai. Make sure const app = express(); is in this function and not before it or it won't recreate.
const express = require('express');
const auth = require('./auth');
const port = 4000;
module.exports = () => {
const app = express();
app.use(auth.session);
app.get('/allowUser2', (req, res) => {
if (!req.user) return res.status(401).send();
if (req.user.user === 2) return res.status(200).send();
});
app.post('/allowUser2', (req, res) => {
if (!req.user) return res.status(401).send();
if (req.user.user === 2) return res.status(200).send();
});
return {
server: app.listen(port).on('listening', () => {
console.log(`HTTP server listening on port ${port}`);
}),
app,
};
};
Then in my tests I can launch the server in before and close the server in after in both tests.
let app;
const sinon = require('sinon');
const auth = require('../../auth.js');
const chai = require('chai');
const chaiHttp = require('chai-http');
const { expect } = chai;
chai.use(chaiHttp);
let server;
describe('route /allowUser2', () => {
before(async () => {
// delete require.cache[require.resolve('../../app.js')]; // causes an error: `Error: listen EADDRINUSE: address already in use`.
sinon.stub(auth, 'session').callsFake((req, res, next) => {
req.user = { user: 2 };
next();
});
server = require('../../app.js')();
agent = chai.request.agent(server.app);
});
after(async () => {
server.server.close(() => {
console.log('Http server closed.');
});
auth.session.restore();
});
it('should allow access', async function () {
const response = await agent.get('/allowUser2');
expect(response.status).to.be.equal(200);
});
});
const chai = require('chai');
const chaiHttp = require('chai-http');
const { expect } = chai;
chai.use(chaiHttp);
let server;
let agent;
describe('route /allowUser2', () => {
before(async () => {
server = require('../../app.js')();
agent = chai.request.agent(server.app);
});
after(async () => {
server.server.close(() => {
console.log('Http server closed.');
});
});
it("shouldn't allow access", async function () {
const response = await agent.get('/allowUser2');
expect(response.status).to.be.equal(401);
});
});
working repo
UPDATE: Proposed Solution https://github.com/DashBarkHuss/mocha_stub_server/pull/1
One problem is the way you are using a direct method reference in app.js prevents Sinon from working. https://gist.github.com/corlaez/12382f97b706c964c24c6e70b45a4991
The other problem (address in use) is because each time we want to get a reference to app, we are trying to create a server in the same port. Breaking that app/server creation into a separate step alleviates that issue.
I´m writing some tests with chai and mocha and i am having some troubles.
For example, in the route that i paste down here, the LOGOUT calls the isLoggedIn middleware that checks if a user exists in the session.
For example, if a do this:
it('Logout', function(done) {
chai.request(baseURL)
.post('/logout')
.end(function(err, res) {
expect(err).to.be.null;
expect(res).to.have.status(204);
done();
});
});
the test faills cause i get a 401 status code. I am new on this test stuffs. I understand that i have to use sinon to get mi test pass, but i can´t get the solution.
This is my route:
'use strict';
const express = require('express');
const createError = require('http-errors');
const router = express.Router();
const bcrypt = require('bcrypt');
const User = require('../models/User');
const {isLoggedIn} = require('../helpers/middlewares');
router.post('/logout', isLoggedIn(), (req, res, next) => {
req.session.destroy();
return res.status(204).send();
});
This is the Middleware:
'use strict';
const createError = require('http-errors');
exports.isLoggedIn = () => (req, res, next) => {
if (req.session.user) {
next();
} else {
next(createError(401));
};
};
Thank you very much!!!
In your flow problem in that express middleware initialized during run express application and after becomes unavailable for stubbing. My solution is that would init stub before run express application.
test.spec.js:
const chai = require("chai"),
sinon = require("sinon"),
chaiHttp = require("chai-http"),
initServer = require("./initTestServer"),
isLoggedInMiddleware = require("./middleware");
chai.use(chaiHttp);
const { expect } = chai;
describe("Resource: /", function() {
before(function() {
sinon.stub(isLoggedInMiddleware, "isLoggedIn").callsFake(function() {
return (req, res, next) => {
next();
};
});
this.httpServer = initServer();
});
after(function() {
this.httpServer.close();
});
describe("#POST /login", function() {
beforeEach(function() {
this.sandbox = sinon.createSandbox();
});
afterEach(function() {
this.sandbox.restore();
});
it("- should login in system and return data", async function() {
return chai
.request(this.httpServer.server)
.post("/logout")
.end((err, res) => {
expect(err).to.be.null;
expect(res).to.have.status(204);
});
});
});
});
initTestServer.js:
const isLoggedInMiddleware = require("./middleware");
const initServer = () => {
const express = require("express");
const app = express();
app.post("/logout", isLoggedInMiddleware.isLoggedIn(), (req, res, next) => {
return res.status(204).send();
});
const server = require("http").createServer(app);
server.listen(3004);
const close = () => {
server.close();
global.console.log(`Close test server connection on ${process.env.PORT}`);
};
return { server, close };
};
module.exports = initServer;
Thank you #EduardS for then answer!!
I solved it in a similar way:
it('Logout', async function(done) {
sinon.stub(helpers, 'isLoggedIn')
helpers.isLoggedIn.callsFake((req, res, next) => {
return (req, res, next) => {
next();
};
})
app = require('../index')
chai.request(app)
.post('/api/auth/logout')
.end(function(err, res2) {
expect(res2).to.have.status(204);
helpers.isLoggedIn.restore()
})
done();
});
In one of my ExpressJS routes, I'm using PassportJS' HTTP Bearer Strategy and Local Strategy together. It means user must be logged in and must have a bearer token to reach that route.
function isLoggedIn(req, res, next) {
// if user is authenticated in the session, carry on
if (req.isAuthenticated())
return next();
// if they aren't redirect them to the home page
res.redirect('/login');
}
app.route('/api/someaction')
.get(passport.authenticate('bearer', { session: false }), isLoggedIn, function(req, res, next) {
console.log(req.user.userID);
});
When I browse to this route with my browser or with Postman (after setting cookies for local strategy) it's working as expected.
Now I need to write integration tests for this route with MochaJS/ChaiJS. This is my test file:
var server = require('../app.js');
var chai = require('chai');
var chaiHttp = require('chai-http');
var should = chai.should();
var expect = chai.expect;
chai.use(chaiHttp);
describe('...', () => {
it('...', (done) => {
chai.request(server)
.get('/api/someaction')
.set('Authorization', 'Bearer 123')
.end((err, res) => {
// asserts here
done();
});
});
});
While testing this file with MochaJS, req.user.userID in /api/someaction is always undefined.
How can I mock PassportJS strategies to get a req.user object inside route?
i am using Express js and Mysql for my application, now i want to start unit testing. I have written this code:
var request = require('supertest');
var server = require('./app');
var chai = require('chai');
var chaiHttp = require('chai-http');
var server = require('./app');
var should = chai.should();
chai.use(chaiHttp);
describe('loading express', function () {
it('responds to /', function testSlash(done) {
request(server)
.get('/')
.expect(200, done);
});
it('404 everything else', function testPath(done) {
request(server)
.get('/foo/bar')
.expect(404, done);
});
it('responds to /customers/getCustomerData', function testPath(done) {
request(server)
.get('/customers/getCustomerData?id=0987654321')
.end(function(err, res){
res.should.have.status(200);
res.body.should.be.a('object');
res.body.status.should.equal("success");
res.body.data.customerId.should.equal("0987654321");
done();
});
});
});
This code is working properly but it makes connection to database and checking all the test cases which i have written, but this is called integration testing i have to do unit testing using mock database. How can i achieve this mocking of database?