Cannot read property 'get' of undefined for unit testing in mocha [closed] - node.js

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
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

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

Related

Why do I get this error TypeError: Cannot read property 'utf8Slice' of undefined [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have no prior knowledge about backend related codes and all so I decided to start recent to learn a few things gradually so I decided to follow a tutorial and now I'm stuck with an error I've researched but cannot still fix.
I have this
const postsSchema = require('./posts')
const resolvers = [
postsSchema.resolvers
]
const typeDefs = [
postsSchema.schema
]
module.exports = {
resolvers,
typeDefs
}
const trendingPosts = require('./mocks/trending')
const featuredPosts = require('./mocks/featured')
const fs = require('fs')
const path = require('path')
module.exports = {
resolvers: {
Query: {
trendingPosts: () => trendingPosts,
featuredPosts: () => featuredPosts,
recentPosts: () => [
...trendingPosts,
...featuredPosts,
...featuredPosts
]
}
},
schema: fs.readFileSync(
path.resolve(
__dirname,
'./posts-schema.graphql'
)
).toString
}
This is my GraphQl
type Query {
trendingPosts: [Post]!
featuredPosts: [Post]!
recentPosts: [Post]!
}
type Post {
id: Int,
title: String
date: String
categories: [String]
author: String
description: String
image: String
}
I'm quite sure I followed the whole process in the tutorial but when I run node app, I get this error in the terminal
buffer.js:778
return this.utf8Slice(0, this.length);
^
TypeError: Cannot read property 'utf8Slice' of undefined
at toString (buffer.js:778:17)
at C:\Users\Natey\Desktop\Code Related\my-app\graphql\node_modules\#graphql-tools\schema\index.cjs.js:195:65
at Array.forEach (<anonymous>)
at concatenateTypeDefs (C:\Users\Natey\Desktop\Code Related\my-app\graphql\node_modules\#graphql-tools\schema\index.cjs.js:191:24)
at buildDocumentFromTypeDefinitions (C:\Users\Natey\Desktop\Code Related\my-app\graphql\node_modules\#graphql-tools\schema\index.cjs.js:231:46)
at buildSchemaFromTypeDefinitions (C:\Users\Natey\Desktop\Code Related\my-app\graphql\node_modules\#graphql-tools\schema\index.cjs.js:213:22)
at makeExecutableSchema (C:\Users\Natey\Desktop\Code Related\my-app\graphql\node_modules\#graphql-tools\schema\index.cjs.js:811:32)
at Object.<anonymous> (C:\Users\Natey\Desktop\Code Related\my-app\graphql\app.js:8:13)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
I need help please, I'll really appreciate it.
As #pzaenger pointed out .toString should be .toString()
Edit:
The key here is to learn to read your stack traces.
buffer.js:778 // This is a node module
return this.utf8Slice(0, this.length);
^
TypeError: Cannot read property 'utf8Slice' of undefined // This is sort of helpful, it's telling use something is trying to access a function utf8Slice of undefined
at toString (buffer.js:778:17) // buffer.js is trying to access utf8Slice on a this object at `toString`
// So now we know a buffer is trying to call utf8Slice on an undefined `this`
// at `toString`. Taking a quick look at your code we see fs.readFileSync(...)
// which gives us a buffer back and then `fs.readFileSync(...).toString`
// experince tells us that toString is a function not a property

How can I import a JS file with window object references in Node.js?

I have a JS file code.js that will be loaded with a website containing code like the following:
window.someObject = window.someObject || {};
window.someObject.someFunction= function(aCondition) {
if (aCondition) someExternalObject.someFunc2();
};
setTimeout(window.someObject.someFunction, 1000);
I can't change this code.
I want to write a unit test for this, so my test file would look something like this:
const expect = require('chai').expect;
var rewire = require('rewire');
var codeModule = require('./path/to/file/code.js');
describe('Test code.js', () => { //Using Mocha.js
//Stub someObject.someFunction
//Test stub with expect()
})
//MORE CODE
This results in ReferenceError: window is not defined since there is no window object in Node.
The reason I'd want to import that module is that I'd want to mock someObject.someFunction for my test.
How can I deal with references to browser APIs like the window object when testing with Node?
Do I need to require a package like this before?
I'm pretty new to this so bear with me if I have some misconceptions here.
Before you import the file do this.
window = window || {}
It will define the window object in the global namespace, but of course with none of the good stuff you get in a browser.

Undefined when trying to use Spy

Using my code:
it('should start application only once', function(done){
var spy = sinon.spy(server, 'startup');
var calledOnce = spy().calledOnce;
calledOnce.should.be.true;
done();
});
I get the error:
Cannot read property should of undefined.
The calledOnce variable is undefined. I'm doing something wrong in how I setup the spy and use it. How can I fix this?
Startup is a method in my object that I exported from a server.js file.
If you want to see if a particular function/method has been called, you need to spy on it before it gets called (otherwise the spy won't know about it):
var server = ...
var spy = sinon.spy(server, 'startup');
server.startup(...);
spy.calledOnce.should.be.true;

Differences between nodejs modules and their exports [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I was just browsing through the nodejs source and noticed differences between the ways different modules are exported. For example, some modules export an object with a prototypical inheritance style:
Thing = function () {
constructor stuff
}
Thing.prototype.jump () {
jump stuff
}
exports = Thing
Where as other modules will append functions directly to exports:
exports.spectacles = function () {
spectacle stuff
}
To me it seems that they will achieve similar goals, but they are clearly different. I believe the first example describes something like an a class, whereas the second simply makes available static methods.
What are the fundamental differences between these two approaches, how are they properly described and what are the advantages/disadvantages of one over the other?
Try viewing this from another perspective: the module which requires your module.
Each file in Node is a module. Each module has a global var, module, and it's property, exports. Whatever you put on that exports property will be available as the module's export.
Primitive
Ie. a boolean, number or a string will work:
module.exports = 3;
When you require that file, you'll get '3'.
var myModule = require('./my-module');
console.log(myModule); // <== 3
But since everything in JavaScript is an object, then you can call methods even a primitive prop:
console.log(myModule.toString()); // <== "3"
Function
You can also export a function.
module.exports = function() {
console.log('3 more');
};
That export will be a function:
var myModule = require('./my-module');
myModule(); // <== '3 more'
Of course, a function is also an object, so you have methods on that too to try out.
console.log(myModule.toString());
// You get: 'function (){\n console.log(\'3 more\');\n }'
Object
Then you can export an object with a few of those things:
module.exports = {
prop: 3,
method: function() {
console.log('Not 3 this time.');
}
};
When you require this module, you'll have that object - an object with a property prop and a method method.
var myModule = require('./my-module');
console.log(myModule.prop); // <== 3
myModule.method(); // <== 'Not 3 this time'
So you get the pattern? Whatever you put in module.exports is what you get on the other end. A matter of perspective, as I've said.
Default
Even if you don't export anything (ie. require an empty file), you have an export.
Require an empty file (it has to exist tho
var myModule = require('./my-module');
console.log(myModule); // <== {}
This tells you that the default export is an empty object.
This is where it gets interesting.
If module.exports = {} by default, then if we simply attach to it, we can add props to it:
So, when Node first gets your module (file), it's a {}. We can simply attach props to it.
module.exports.prop = 3;
module.exports.method = function() { console.log('I am out of ideas for placeholders, I should use kitten');}
Why does it work without the module keyword?
Now, why does this work without the module keyword? Ie. just:
exports.prop = 3;
exports.method = function() {};
Because when the Node.js starts working your file, it aliases exports to module.exports. But be careful, you can override this!
What does that mean? It's almost as if you wrote var exports = module.exports at the beginning of the file.
So you can use just the exports syntax, but I prefer not to. Why? Because you can make a mistake and override exports var. And you'll be more careful with module.exports. (There are other reasons, this one is what I have learned about first and remembered best.)
Example 1:
exports.prop = false;
// later in module
module.exports = myObj; // see? overriden.
Example 2:
var exports = {}; // see? Overridden default module.exports.
exports.prop = 4;
exports.method = function(){
console.log('3 more');
};
So when you require this later:
var myModule = require('./my-module');
console.log(myModule); // <== {}
I hope this helps.
The differences that you are pointing out are mainly flavour based. It is very related with how people prefer to construct their objects.
Javascript has lot's of different ways to build objects, here is another example:
exports.stuff = {
f1: function() ...
foobar: function() ...
}
For example, I prefer to wrap everything with a function to enforce use strict and simulate static variables:
(function() {
"use strict";
var staticVariable;
function MyObject() {
...
};
exports.MyObject = MyObject;
})();
+1 on close vote. This question is very subjective.

Mongoose Trying to open unclosed connection

This is a simplified version of the problem, but basically I'm trying to open 2 mongodb connections with mongoose and it's giving me "Trying to open unclosed connection." error.
Code sample:
var db1 = require('mongoose');
db1.connect('my.db.ip.address', 'my-db');
var db2 = require('mongoose');
db2.connect('my.db.ip.address', 'my-db');
db2.connection.close();
db1.connection.close();
Any idea how to make it work?
connect() opens the default connection to the db. Since you want two different connections, use createConnection().
API link: http://mongoosejs.com/docs/api.html#index_Mongoose-createConnection
To add on Raghuveer answer :
I would also mention that instead of using mongoose directly (you are probably using it this way you end up on this post) :
require('mongoose').model(...);
You would use the returned connection :
var db = require('mongoose').connect('xxx', 'yyy');
db.model(...);
I get this issue while running my tests.
This is what I did to solve it.
//- in my app.js file.
try {
mongoose.connect('mongodb://localhost/userApi2'); //- starting a db connection
}catch(err) {
mongoose.createConnection('mongodb://localhost/userApi2'); //- starting another db connection
}
I had this problem doing unit test with mocha.
The problem came when I added a second test because beforeEach is called twice.
I've solved this with this code:
const mongoose = require('mongoose');
describe('Your test suite', () => {
beforeEach( () => {
if (mongoose.connection.db) {
return; // or done();
} else {
// connect to mongodb
});
describe('GET /some-path', () => {
it('It should...', () => {
});
});
describe('POST /some-path', () => {
it('It should...', () => {
});
});
});
Hope it helps you!
You are attempting to open the default connection ( which is not yet closed ) a 2nd time.
do the following instead
var db = require('mongoose'); //note only one 'require' needed.
var connectionToDb1 = db.createConnection('my.db1.ip.address', 'my-db1');
var connectionToDb2 = db.createConnection('my.db2.ip.address', 'my-db2');
Using mongoose.disconnect(fn):
mongoose.disconnect(() => {
// here it would be possible "reset" models to fix
// OverwriteModelError errors
mongoose.models = {};
// here comes your logic like registering Hapi plugins
server.register(somePlugin, callback);
});
I found this question typing the error message and despite my problem is a bit different I believe it could be useful for those using Hapi. More specifically Hapi + rest-hapi + mocha.
When running mocha with --watch option I was facing both: OverwriteModelError and Error: Trying to open unclosed connection errors.
Simple Solution -
Use mongoose.createConnection() instead of mongoose.connect()
Its occurs because of version issue

Resources