I am using a route module that accepts http requests to view items in a catalog where the handler depends on a model module to retrieve item data :
/routes/viewCatalogRoute.js
var ViewCatalogModel = require('../models/viewCatalogModel').ViewCatalogModel;
var viewCatalogModel = new ViewCatalogModel();
exports.routes = function (server) {
server.get('/catalog/view/item/:itemId', viewCatalogHandler);
};
function viewCatalogHandler(request, response) {
viewCatalogModel.retrieveItem(request.params.itemId, function(err, item) {
if (err) {
response.send(500, {error: 'failed to retrieve item});
} else {
response.send(200, {item: item});
}
});
}
I want to write a test of the /catalog/view/item/:itemId endpoint, since the db is not available in the test-context, the catalogDataModel.retrieveItem() must be mocked to avoid attempting a call to db. I thought I could use proxyquire to accomplish this :
ViewCatalogTests.js
var agent = require('superagent');
var proxyquire = require('proxyquire');
var publishModel = require(loadPath + 'models/publishModel');
describe.only('viewcatalog endpoint', function () {
var serverHandler = {};
var stubViewCatalogModule = {};
//fire-up express server
before(function () {
var server = require('./server');
serverHandler = server.listen(port);
});
beforeEach(function (done) {
stubViewCatalogModel.ViewCatalogModel = function ViewCatalogModel () {};
stubViewCatalogModel.ViewCatalogModel.prototype.retrieveItem = function retrieveItem(itemId, cb) {
cb(null, new {id:1, description:'blah'});
};
var viewCatalogModel = proxyquire('./routes/viewCatalogRoute', {
'../models/viewCatalogModel': stubViewCatalogModel;
});
});
it.only('retrieves item from catalog as expected', function (done) {
agent.post('localhost:80//catalog/view/item/1', function (res) {
setTimeout(function () {
expect(res.statusCode).to.equal(200);
expect(res.text).to.equal.(JSON.stringify({item: {id:1, description:'blah'}}));
done();
}, 100);
However the test fails on attempting to connect to db -- apparently proxyquire in fact is not mocking viewCatalogModel.retrieveItem() and the actual code is being run.
Can proxyquire be used to to mock a dependency of a http request handler module ?