Sample code:
function TestClass() {
var this.name = 'test';
var this.host = '...';
var this.port = '...';
//...
this.connection = this.createConnection(....);
}
TestClass.prototype.testFunc = function(data) {
if(data == this.name) {
return true;
} else {
return false;
}
}
Testclass.prototype.createConnection = function (...) {
//some code
//a real HTTP connection will be created
//some code
}
Now I want to test testFunc, it has a class variable this.name, so I have to create a TestClass instance. But if I create TestClass instance, a real HTTP connection will be created. How can I avoid this real HTTP connection when testing?
In situation like this, how can I write the test code?
Try to simply re-define createConnection in your test, before you instantiate TestClass.
TestClass.prototype.createConnection = function() {
console.log("Called redefined createConnection");
}
You should mock the dependency that make the request not your class you wanna test. Take a look at this nock, a HTTP mocking and expectations library