【问题标题】:Is there a spyOn analogue in QUnit?QUnit 中有 spyOn 类似物吗?
【发布时间】:2012-02-10 18:53:20
【问题描述】:

我正在为 Jasmine 和 QUnit 的不同测试用例编写规范以比较它们,在我需要编写测试以检查事件是否绑定到元素之前,它们看起来相同。

事件绑定的样子

$('.page').live('click', function() { page_clicked( $(this) ) });

page_clicked 是一个私有方法,但它需要另一个模块的公共方法。

这是 Jasmine 规格:

it('should bind events to pages', function() {
    spyOn( search, 'get_results' );

    $('.page:eq(0)').trigger('click');

    expect( search.get_results ).toHaveBeenCalled();
});

此测试有效。现在我正在尝试为 QUnit 编写相同的测试,但找不到任何类似于 spyOn 的东西。如何为 QUnit 编写这个测试?

【问题讨论】:

    标签: javascript unit-testing jasmine qunit spy


    【解决方案1】:

    这是因为 QUnit 没有间谍或模拟。但是您可以使用Sinon.JS 模拟框架。你的测试应该像这样使用sinon spy:

    var spy = sinon.spy(search, 'get_results');
    sinon.assert.calledOnce(spy);
    

    【讨论】:

    • 试图复制/粘贴您的代码,但 assert(spy.calledOnce) 抛出 assert is not definedsinon.assert.called( spy ) 抛出 expected get_results to have been called at least once but was never called
    • 好的,它是从 sinon doku 复制/粘贴的,我已修复。
    • 还是不行。 expected get_results to be called once but was called 0 times。我在 page_clicked 函数中调用 get_results 后发出警报,警报提示,Jasmine 测试通过但 QUnit + SinonJS 没有。
    • 哦,它有效,我只是在错误的地方插入了trigger('click')。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-23
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多