如何访问此Javascript属性?
我需要确保调用了下面显示的如何访问此Javascript属性?,javascript,unit-testing,mocking,sinon,Javascript,Unit Testing,Mocking,Sinon,我需要确保调用了下面显示的UserMock-类中的某个方法。我创建这个模拟版本是为了注入到另一个模块中,以防止测试期间出现默认行为 我已经在使用sinon.js,那么如何访问isValid()等方法并用spy/stub替换它呢?是否可以在不实例化类的情况下执行此操作 var UserMock = (function() { var User; User = function() {}; User.prototype.isValid = function() {}; return
UserMock
-类中的某个方法。我创建这个模拟版本是为了注入到另一个模块中,以防止测试期间出现默认行为
我已经在使用sinon.js
,那么如何访问isValid()
等方法并用spy/stub替换它呢?是否可以在不实例化类的情况下执行此操作
var UserMock = (function() {
var User;
User = function() {};
User.prototype.isValid = function() {};
return User;
})();
多谢各位
var UserMock = (function() {
var User;
User = function() {};
User.prototype.isValid = function() {};
return User;
})();
只需通过
原型
:
(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);
说明:
(function(_old) {
及
将方法isValue
引用到变量\u old
。闭包是这样做的,这样我们就不会用变量来调用父作用域
UserMock.prototype.isValid = function() {
重新声明原型方法
return _old.apply(this, arguments); // Make sure to call the old method without anyone noticing
调用旧方法并从中返回结果
使用apply可以将所有参数传递给函数,并将其放入正确的范围(this
)
如果我们做一个简单的函数并应用它
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
只需通过
原型
:
(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);
说明:
(function(_old) {
及
将方法isValue
引用到变量\u old
。闭包是这样做的,这样我们就不会用变量来调用父作用域
UserMock.prototype.isValid = function() {
重新声明原型方法
return _old.apply(this, arguments); // Make sure to call the old method without anyone noticing
调用旧方法并从中返回结果
使用apply可以将所有参数传递给函数,并将其放入正确的范围(this
)
如果我们做一个简单的函数并应用它
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
你忘了返回结果。你介意告诉我在哪里可以找到关于它如何工作的解释吗?我从来没有见过这种语法before@Industrial忽略
返回结果。
部分。您忘了返回结果。您介意告诉我在哪里可以找到有关此操作的解释吗?我从未见过此语法before@Industrial忽略返回结果。
部分。