问题
I need to make sure that a certain method inside the below shown UserMock
-class was called. I've created this mock version to inject into another module to prevent default behaviour during testing.
I am already using sinon.js
, so how can I access a method such as isValid()
and replace it with a spy/stub? Is it possible to do this without instantiating the class?
var UserMock = (function() {
var User;
User = function() {};
User.prototype.isValid = function() {};
return User;
})();
Thank you
回答1:
var UserMock = (function() {
var User;
User = function() {};
User.prototype.isValid = function() {};
return User;
})();
Simply via 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 method isValue
to the variable _old
. The closure is made so we don't pulede the parent scope with the variable.
UserMock.prototype.isValid = function() {
Redeclares the prototype method
return _old.apply(this, arguments); // Make sure to call the old method without anyone noticing
Calling the old method and returning the result from it.
Using apply lets put in the right scope (this
) with all the arguments passed to the function
Eg. 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
来源:https://stackoverflow.com/questions/13383345/how-do-i-access-this-javascript-property