Ajitej Kaushik Ajitej Kaushik - 4 months ago 21
Node.js Question

Cannot read property 'get' of undefined for unit testing in mocha

I am trying to write a unit test over my file routes.js using mocha and chai. I have defined a function in routes.js and has defined a test file in which my test case is there.

When i am running my test case, its showing the error

TypeError: Cannot read property 'get' of undefined


My code for test.js is

var expect = require('chai').expect;
var chai = require('chai');
var app = ('../api/smartAccount/identifyLoan/getDirectDebitTrans/routes');

describe("Unit testing for function", function(){
it("Testing the function using mocha", function(done){
var req = {
queryString: 101
};

var test = app.getUser.get(req);
expect(test).to.be.an('undefined');
done();
});
});


I am passing req as i am expecting req.queryString.id in my routes.js .

code of routes.js is

var config = require("../../../../serverConfig/config");

module.exports = {
getUser: {
get: function(req, parameters, environment) {

var id = req.queryString.id;

//functionality
});
}
}


Please help where i am going wrong.

p.s get function is fetching data from DB but i havent mentioned the bd connection as i feel its of irrelevance here.
TIA

Answer

Nothing scary here. You are missing the require keyword in test.js's

var app = ('../api/smartAccount/identifyLoan/getDirectDebitTrans/routes');

Hence;

var expect = require('chai').expect;
var chai = require('chai');
var app = require('../api/smartAccount/identifyLoan/getDirectDebitTrans/routes');

Will fix it.

Without the require keyword, variable app is just a string with value of ../api/smartAccount/identifyLoan/getDirectDebitTrans/routes' and the code dies when it tries to access the non-existence get property. And this is evidently shown in your error message TypeError: Cannot read property 'get' of undefined

Comments