【问题标题】:How do I access this Javascript property?如何访问此 Javascript 属性?
【发布时间】:2012-11-14 16:50:23
【问题描述】:

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

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

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

谢谢

【问题讨论】:

    标签: javascript unit-testing mocking sinon


    【解决方案1】:
    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);
    

    将方法isValue 引用到变量_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
    

    【讨论】:

    • 你忘记返回结果了。
    • 你介意告诉我在哪里可以找到关于它如何工作的解释 - 我以前从未见过这种语法
    • @Industrial 忽略 return the result. 部分。
    猜你喜欢
    • 1970-01-01
    • 2013-04-27
    • 2013-06-19
    • 1970-01-01
    • 2019-09-25
    • 2012-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多