express middleware testing mocha chai - node.js

Is there a way to test those kind of middleware in express:
module.exports = function logMatchingUrls(pattern) {
return function (req, res, next) {
if (pattern.test(req.url)) {
console.log('request url', req.url);
req.didSomething = true;
}
next();
}
}
The only middleware testing i found was:
module.exports = function(request, response, next) {
/*
* Do something to REQUEST or RESPONSE
**/
if (!request.didSomething) {
console.log("dsdsd");
request.didSomething = true;
next();
} else {
// Something went wrong, throw and error
var error = new Error();
error.message = 'Error doing what this does'
next(error);
}
};
describe('Middleware test', function(){
context('Valid arguments are passed', function() {
beforeEach(function(done) {
/*
* before each test, reset the REQUEST and RESPONSE variables
* to be send into the middle ware
**/
requests = httpMocks.createRequest({
method: 'GET',
url: '/css/main.css',
query: {
myid: '312'
}
});
responses = httpMocks.createResponse();
done(); // call done so that the next test can run
});
it('does something', function(done) {
/*
* Middleware expects to be passed 3 arguments: request, response, and next.
* We are going to be manually passing REQUEST and RESPONSE into the middleware
* and create an function callback for next in which we run our tests
**/
middleware(responses, responses, function next(error) {
/*
* Usually, we do not pass anything into next except for errors, so because
* in this test we are passing valid data in REQUEST we should not get an
* error to be passed in.
**/
if (error) { throw new Error('Expected not to receive an error'); }
// Other Tests Against request and response
if (!responses.didSomething) { throw new Error('Expected something to be done'); }
done(); // call done so we can run the next test
}); // close middleware
}); // close it
}); // close context
}); // close describe
This work well with the simple middleware (it like testing basic function with callback) provided above but with more complex middleware i cannot get it work. Is it possible to test this kind of middleware?

Here's a simple setup that you could use, using chai and sinon:
var expect = require('chai').expect;
var sinon = require('sinon');
var middleware = function logMatchingUrls(pattern) {
return function (req, res, next) {
if (pattern.test(req.url)) {
console.log('request url', req.url);
req.didSomething = true;
}
next();
}
}
describe('my middleware', function() {
describe('request handler creation', function() {
var mw;
beforeEach(function() {
mw = middleware(/./);
});
it('should return a function()', function() {
expect(mw).to.be.a.Function;
});
it('should accept three arguments', function() {
expect(mw.length).to.equal(3);
});
});
describe('request handler calling', function() {
it('should call next() once', function() {
var mw = middleware(/./);
var nextSpy = sinon.spy();
mw({}, {}, nextSpy);
expect(nextSpy.calledOnce).to.be.true;
});
});
describe('pattern testing', function() {
...
});
});
From there, you can add more elaborate tests for the pattern matching, etc. Since you're only using req.url, you don't have to mock an entire Request object (as created by Express) and you can just use a simple object with a url property.

I used node-mocks-http to unit test my middleware. Here's my code:
function responseMiddleware(req, res, next) {
res.sendResponse = (...args) => {
//<==== Code removed from here
};
next();
}
And in my spec file I did it like this:
var expect = require('chai').expect;
var sinon = require('sinon');
var responseMiddleware = require('./response');
var httpMocks = require('node-mocks-http');
describe('request handler calling', function() {
it('should call next() once', function() {
var nextSpy = sinon.spy();
responseMiddleware({}, {}, nextSpy);
expect(nextSpy.calledOnce).to.be.true;
});
it('should add sendResponse key', function() {
var nextSpy = sinon.spy();
var req = httpMocks.createRequest();
var res = httpMocks.createResponse();
responseMiddleware(req, res, nextSpy);
expect(nextSpy.calledOnce).to.be.true;
responseMiddleware(req, res, () => {
expect(res).to.have.property('sendResponse');
})
});
});
If you are using async calls then you can use await and then call done() after that.

Related

Correct way to unit test Express Middleware [duplicate]

This question already has answers here:
express middleware testing mocha chai
(2 answers)
Closed 6 years ago.
I have a piece of Express middleware that is set to check for a valid Content-Type header in all of my POST requests that hit my server, the code for this middleware is below:
import * as STRINGS from "../Common/strings";
function ContentTypeValidator(req, res, next) {
let contentHeader = req.get("content-type");
if(!contentHeader) {
res.status(400).send(STRINGS.ERROR_CONTENT_TYPE_MISSING);
} else {
if(contentHeader.toLowerCase() !== "application/json") {
res.status(415).send(STRINGS.ERROR_CONTENT_TYPE_UNSUPPORTED);
} else {
next();
}
}
}
export default ContentTypeValidator;
I am using mocha, chai and node-mocks-http for my TDD and my question surrounds the tests when next() will not be called as res.send() will handle the ending of this request for me.
it("Should return 200 for valid Content-Type header", (done) => {
req = nodeMocks.createRequest({
headers: {
"Content-Type": "application/json"
}
});
ContentTypeValidator(req, res, (err) => {
res.statusCode.should.equal(200);
expect(err).to.be.undefined;
done();
});
});
it("Should return 400 if Content-Type header is missing", (done) => {
ContentTypeValidator(req, res, () => {});
res.statusCode.should.equal(400);
res._getData().should.equal("Content-Type header missing");
done();
});
In the first test above, I am expecting this to pass, so I pass in a function to act as the next() function and this test passes. In the second test, I am expecting this to fail so if I pass in a function then mocah complains that the test has exceeded 2000ms as the callback function is never called, which is to be expected since res.send() is handling it in this instance.
Is the way I've written the second test correct when it comes to unit testing Express middleware like this or is there a better/more advisable way to do this?
EDIT: So just to clarify, I am focused on wanting to test the middlewear when the next callback will NOT be called, the question I'm apparently duplicating is looking at using sinon to check if next is called. I am looking to see how to unit test when the callback function will NOT be called.
Check out this answer
https://stackoverflow.com/a/34517121/4996928
var expect = require('chai').expect;
var sinon = require('sinon');
var middleware = function logMatchingUrls(pattern) {
return function (req, res, next) {
if (pattern.test(req.url)) {
console.log('request url', req.url);
req.didSomething = true;
}
next();
}
}
describe('my middleware', function() {
describe('request handler creation', function() {
var mw;
beforeEach(function() {
mw = middleware(/./);
});
it('should return a function()', function() {
expect(mw).to.be.a.Function;
});
it('should accept three arguments', function() {
expect(mw.length).to.equal(3);
});
});
describe('request handler calling', function() {
it('should call next() once', function() {
var mw = middleware(/./);
var nextSpy = sinon.spy();
mw({}, {}, nextSpy);
expect(nextSpy.calledOnce).to.be.true;
});
});
describe('pattern testing', function() {
...
});
});

sinon spy as callback not being called

I have my source file for which i have written test cases for
var debug = require('debug')('kc-feed:source:fb');
var request = require('request');
var config = require('../../config').root;
exports.source = function fetchFeed (callback) {
var params = {
headers: {'content-type' : 'application/jsons'},
url: config.host + "v1/social/fb/sync_feed",
method: 'GET'
};
request(params, function(err, body, response) {
if(err) {
callback(err);
}
else {
var raw_data = JSON.parse(response);
callback(null, raw_data);
}
});
};
This is my mocha test case
var chai = require('chai'),
expect = chai.expect,
app = require('../app'),
rewire = require('rewire'),
fbfeed = rewire('../src/feed/source/fb_feed'),
supertest = require('supertest'),
sinon = require('sinon'),
nock = require('nock');
describe('test cases for fb feed file', function() {
var callback;
beforeEach(function(){
callback = sinon.spy();
});
after(function(){
nock.cleanAll();
});
it('callback should be called with the response', function(done) {
nock('http://localhost:3000/')
.get('/v1/social/fb/sync_feed')
.reply(200, {});
callback = sinon.spy();
fbfeed.source(callback);
sinon.assert.calledOnce(callback);
done();
});
it('callback should be called with the error', function(done) {
nock('http://localhost:3000/')
.get('/v1/social/fb/sync_feed')
.replyWithError(new Error('err'));
fbfeed.source(callback);
sinon.assert.calledOnce(callback);
done();
});
Both my test cases fail as it says that callback is called 0 times. But the callback is always called. Please help.
It looks like the requests are still being performed asynchronously (I can't definitively say if this is expected when using nock), so you can't use spies like that.
Provide a regular callback instead:
fbfeed.source(function(err, raw_data) {
...make your assertions...
done();
});

NodeJS: How to test middleware making external call

I have an authentication middleware I will like to test, the middleware makes an external call to an authentication service and based on the returned statusCode either calls the next middleware/controller or it returns a 401 status. Something like what I have below.
var auth = function (req, res, next) {
needle.get('http://route-auth-service.com', options, function (err, reply) {
if (reply.statusCode === 200) {
next();
} else {
res.statusCode(401)
}
})
}
I use SinonJS, nock, and node-mocks-http for testing and my simple test is as below.
// require all the packages and auth middleware
it('should login user, function (done) {
res = httpMocks.createResponse();
req = httpMocks.createRequest({
url: '/api',
cookies: {
'session': true
}
});
nock('http://route-auth-service.com')
.get('/')
.reply(200);
var next = sinon.spy()
auth(res, req, next);
next.called.should.equal(true); // Fails returns false instead
done();
});
The test always fails and returns false, I feel that the reason is because the needle call is asynchronous, and before the call returns the assertion part is reached. I have been working on this all day, I need help please.
you need to split the test setup away from the assertion
// this may be "beforeEach"
// depends on what testing framework you're using
before(function(done){
res = httpMocks.createResponse();
req = httpMocks.createRequest({
url: '/api',
cookies: {
'session': true
}
});
nock('http://route-auth-service.com').get('/').reply(200);
var next = sinon.spy();
auth(res, req, function() {
next();
done();
});
});
it('should login user', function () {
next.called.should.equal(true); // Fails returns false instead
});

Grab specific response properties from SuperTest

I want to be able to grab some response properties and throw them into a variable at times with SuperTest. How can I do this? I don't see the docs doing anything but assertions on the response.
for example I'd like to do something like this:
var statusCode = request(app).get(uri).header.statusCode;
I'd like to do something like this. Because sometimes I like to split out the asserts into seperate Mocha.js it() tests due to the fact I'm doing BDD and so the 'Thens' in this case are based on the expected response parts so each test is checking for a certain state coming back in a response.
for example I'd like to do this with supertest:
var response = request(app).get(uri);
it('status code returned is 204, function(){
response.status.should.be....you get the idea
};
it('data is a JSON object array', function(){
};
Here is an example how you can accomplish what you want:
server file app.js:
var express = require('express');
var app = express();
var port = 4040;
var items = [{name: 'iphone'}, {name: 'android'}];
app.get('/api/items', function(req, res) {
res.status(200).send({items: items});
});
app.listen(port, function() {
console.log('server up and running at %s:%s', app.hostname, port);
});
module.exports = app;
test.js:
var request = require('supertest');
var app = require('./app.js');
var assert = require('assert');
describe('Test API', function() {
it('should return 200 status code', function(done) {
request(app)
.get('/api/items')
.end(function(err, response) {
if (err) { return done(err); }
assert.equal(response.status, 200);
done();
});
});
it('should return an array object of items', function(done) {
request(app)
.get('/api/items')
.end(function(err, response) {
if (err) { return done(err); }
var items = response.body.items;
assert.equal(Array.isArray(items), true);
done();
});
});
it('should return a JSON string of items', function(done) {
request(app)
.get('/api/items')
.end(function(err, response) {
if (err) { return done(err); }
try {
JSON.parse(response.text);
done();
} catch(e) {
done(e);
}
});
});
});
You can see some examples here on the superagent github library since supertest is based on superagent library.

Testing functions that contains async calls

I'm trying to test the get function:
exports.get = function(req, res) {
Subscriptions
.find(req.params.id)
.success(function(subscription) {
if (subscription) {
res.json({message: "Success"}, 200);
} else {
res.json({message: "Not found"}, 404);
}
})
.error(function(error) {
res.json({message: "Internal server error"}, 500);
});
};
Specifically, I don't really care if it hits the database, I only want to test the scenarios where the success and error events occur. I'm using sequelize.js as my orm to handle the database. I've gotten a test up and running, but its a bit nasty, with the timeout. Is there a better way of doing this? Here's the test I've written so far:
var express = require('express')
, sinon = require('sinon')
, subscription = require('app/controllers/subscriptions')
, Subscriptions = require('app/models/subscriptions')
;
describe('subscription controller', function() {
beforeEach(function() {
this.mockResponse = sinon.mock(express.response);
});
afterEach(function() {
this.mockResponse.restore();
});
describe('GET /subscriptions/:id', function() {
it('should return a json response', function(done) {
var request = {
params: {
id: 'identifier'
}
};
var expectedResponse = {
subscriptions_uri : "/subscription/identifier"
};
this.mockResponse
.expects('json')
.once()
.withArgs(expectedResponse);
subscription.get(request, express.response);
setTimeout(function() {
done();
}, 500);
});
});
});
I decided to use the supertest library, which made testing my controller incredibly easy:
var express = require('express')
, subscription = require('app/controllers/subscriptions')
, request = require('supertest')
, app = express()
;
describe('subscription controller', function() {
describe('GET /subscriptions/:id', function() {
it('should return a json response', function(done) {
var expectedBody = {
subscriptions_uri : "/subscription/identifier"
};
request(app)
.get('/subscriptions/identifier')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(expectedBody)
.expect(200, done);
});
});
});

Resources