How to access this Javascript property?

I need to make sure that a specific method has been called inside the UserMock -class below. I created this mock version for input into another module to prevent the default behavior during testing.

I already use sinon.js , so how can I access a method like isValid() and replace it with a spy / stub? Can this be done without instantiating the class?

 var UserMock = (function() { var User; User = function() {}; User.prototype.isValid = function() {}; return User; })(); 

thanks

0
source share
1 answer
 var UserMock = (function() { var User; User = function() {}; User.prototype.isValid = function() {}; return User; })(); 

Just through prototype :

 (function(_old) { UserMock.prototype.isValid = function() { // my spy stuff return _old.apply(this, arguments); // Make sure to call the old method without anyone noticing } })(UserMock.prototype.isValid); 

Explanation:

 (function(_old) { 

and

 })(UserMock.prototype.isValid); 

Makes a reference to the isValue method on the isValue variable. Closing is done so that we do not change the parent area with the variable.

 UserMock.prototype.isValid = function() { 

Updates the prototype method.

 return _old.apply(this, arguments); // Make sure to call the old method without anyone noticing 

Call the old method and return the result from it.

Using apply allows you to put in the desired area ( this ) all the arguments passed to the function. For example. if we make a simple function and apply it.

 function a(a, b, c) { console.log(this, a, b, c); } //a.apply(scope, args[]); a.apply({a: 1}, [1, 2, 3]); a(); // {a: 1}, 1, 2, 3 
+3
source

All Articles