【问题标题】:Mocking 'this' in javascript qunit在 javascript qunit 中模拟“this”
【发布时间】:2014-02-20 05:05:53
【问题描述】:

如果我有一个 Javascript 函数使用,像这样...$(this)[0].element.id;

updateElement(){
$(this)[0].element.id;
}

我正在使用 Qunit,有什么方法可以模拟 'this' 我希望能够测试这个功能。

【问题讨论】:

  • 你有更大的代码示例吗?
  • 代码异味,将此作为 updateElement 的参数,它将是可测试的。测试的目标是重构糟糕的代码:blog.testdouble.com/posts/…

标签: javascript unit-testing qunit grunt-contrib-qunit


【解决方案1】:

通过Function对象的applycall函数,可以在调用函数时改变this的值:

var mock = ...

updateElement.call(mock);

this 将在上面的updateElement 调用中引用mock

【讨论】:

    【解决方案2】:

    我假设,this 指的是一些 jQuery 对象。您可以使用 jQuery 函数创建相应的对象,然后使用 bind() 将对象作为 this 附加到您的实际函数:

    // prepare the DOM objects
    var $elem = $( '...' );
    
    // prepare a bound function
    var boundFct = updateElement.bind( $elem );
    
    // execute your function
    boundFct();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-08
      • 1970-01-01
      • 1970-01-01
      • 2011-07-09
      • 2020-03-08
      • 1970-01-01
      相关资源
      最近更新 更多