Skip to content

Instantly share code, notes, and snippets.

@dylanjha
Last active January 1, 2016 15:49
Show Gist options
  • Select an option

  • Save dylanjha/8166529 to your computer and use it in GitHub Desktop.

Select an option

Save dylanjha/8166529 to your computer and use it in GitHub Desktop.
Am I doing this wrong? My goal here is to set up a constructor that I can test. The first bit is how I would normally create this new constructor MyObject... the second bit shows how I have to change it in order to test some of the internal functions. See my first comment below.
//this constructor, MyObject is supposed to only have 1 publically exposed method: .getResults()
;(function ( $, window, document, undefined ) {
window.MyObject = function(params){
var error = params.error;
function _shouldFireRequest = function(){
//some logic
return boolean
}
function _requestResults = function(){
//makes a request
}
this.getResults = function(){
if(_shouldFireRequest()){
_requestResults();
} else {
error()
}
}
}
})(jQuery, window, document);
// if I want to test the _shouldFireRequest method, I need to expose it
// as a method on the object as shown below.
// My strategy is that once I expose it, I can create a new instance of MyObject:
// myObject = new MyObject
// set up some state on that instance, then call myObject._shouldFireRequest()
// and test an expectation on the return value.
;(function ( $, window, document, undefined ) {
//
//same
//
this._shouldFireRequest = function(){
//some logic
return boolean
}
this.getResults = function(){
if(this._shouldFireRequest()){
_requestResults();
} else {
error()
}
}
///
})(jQuery, window, document);
@dylanjha
Copy link
Author

dylanjha commented Jan 2, 2014

Thanks so much. This is really helpful. In my case. I DO want to have multiple instances of this MyObject... that means, I will use the prototype strategy.

The main takeaway here, that perfectly answers my question is that instead of this._method, like I was doing, I should put those methods on the prototype.

That way, they're kinda from the main constructor, but more importantly they're exposed be able to test in isolation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment