如何访问此Javascript属性? [英] How do I access this Javascript property?

查看:86
本文介绍了如何访问此Javascript属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要确保在下面显示的UserMock类中调用了某个方法.我已经创建了该模拟版本以注入到另一个模块中,以防止在测试期间出现默认行为.

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.

我已经在使用sinon.js,那么如何访问诸如isValid()之类的方法并将其替换为间谍/存根?是否可以在不实例化类的情况下做到这一点?

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;
})();

谢谢

推荐答案

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


只需通过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);


说明:

(function(_old) {

})(UserMock.prototype.isValid);

对变量_old的方法isValue进行引用.进行了封闭操作,因此我们不会在父范围内使用该变量.

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() {

重新声明原型方法

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.

使用apply命令将所有参数都传递到函数中,将其放入正确的范围(this)
例如.如果我们做一个简单的函数并应用它.

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

这篇关于如何访问此Javascript属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆