【问题标题】:Spy on function that's called on click event监视点击事件调用的函数
【发布时间】:2015-07-27 12:39:20
【问题描述】:

我做错了什么?试图监视在元素单击事件上调用的函数,但测试总是返回 false。

规格:

describe('button', function() {
  before(function() {
    this.spy = sinon.spy(window, 'testMethod');
  });

  it('Should call testMethod', function() {
    $('#testBtn').click();

    expect(this.spy.called).to.equal(true);
  });
});

js:

$('#testBtn').on('click', testMethod);

function testMethod() {
  return true;
}

【问题讨论】:

    标签: javascript mocha.js sinon chai karma-mocha


    【解决方案1】:

    问题是由于这一行:

    $('#testBtn').on('click', testMethod);
    

    在设置间谍之前获取对testMethod 的引用。所以它获取对原始函数的引用,而不是间谍,然后您在window.testMethod 上设置间谍并不重要,因为在点击事件上调用的函数始终是原始testMethod。您可以通过以下几种方式进行测试:

    1. 运行$('#testBtn').on('click', testMethod); 你设置了间谍。例如,您可以将它放在您的 before 挂钩中。

    2. $('#testBtn').on('click', testMethod); 更改为$('#testBtn').on('click', function () { testMethod(); });。每次处理单击事件时,匿名函数都会获取对testMethod 的新引用。因此,一旦您设置它,它将获取对间谍的引用。

    我已经通过创建一个复制您的代码的测试并使用上面的两个修复来测试我在这里所说的内容。

    【讨论】:

      【解决方案2】:

      试试

      expect(this.spy).to.have.been.called();
      

      而不是

      expect(this.spy.called).to.equal(true);
      

      【讨论】:

      • 不,这不是解决方案。看我的回答。 expect(this.spy).to.have.been.called(没有括号:它不是函数调用;请参阅它的文档)只是编写expect(this.spy.called).to.equal(true); 的不同方式@ 两者在功能上是等效的:它们将在相同的情况下失败并在相同的情况下通过。
      • 哎呀!我错误地添加了括号。有趣...不知道两者是等价的。
      猜你喜欢
      • 1970-01-01
      • 2018-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-17
      • 1970-01-01
      • 2019-07-01
      相关资源
      最近更新 更多