Last active
January 1, 2016 15:49
-
-
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 file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //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); | |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.