【问题标题】:Reusing Jasmine Spy with different andCallFake() method使用不同的 andCallFake() 方法重用 Jasmine Spy
【发布时间】:2014-04-24 10:25:08
【问题描述】:

我正在尝试在 jasmine(1.3 版)中编写一些高级测试,其中我在 $.getJSON() 方法上设置了一个间谍。这是在此处看到的beforeEach 块中设置的:

describe 'the Controller', ->
    beforeEach ->
    Fixtures.createTestData()
    jqXHR = Fixtures.jqXHR
    section = new section({el:appDom})

    response = Fixtures.createSectionsSearchResponse()
    spyOn($, 'getJSON').andCallFake( ->
        jqXHR.resolve(response)
    )

然后我像往常一样浏览搜索查询(效果很好)。

在我后来的一个测试中,我有第二个 API 被 ping 通。我想更改正在发送的响应,但似乎无法正常工作。 This Blog 似乎暗示我可以用不同的andCallFake() 重用间谍,但它似乎不起作用。我得到的是原始响应对象而不是我的重写方法

    $.getJSON.andCallFake( ->
        jqXHR.resolve({"count":4})
    )

有什么想法可以重用或销毁原来的 spy on 方法吗?

【问题讨论】:

    标签: coffeescript jasmine


    【解决方案1】:

    你可以重置间谍。

    来自Jasmine guide

    it("can be reset", function() {
        foo.setBar(123);
        foo.setBar(456, "baz");
    
        expect(foo.setBar.calls.any()).toBe(true);
    
        foo.setBar.calls.reset();
    
        expect(foo.setBar.calls.any()).toBe(false);
    });
    

    【讨论】:

    • 我应该说,我使用的是 1.3。我们还没有升级到 2.0。很抱歉!
    • Jasmine 1.3 中也存在重置间谍
    • Jasmine 1.3 文档没有提及重置间谍,您的示例似乎不起作用。
    • 你可以在 Jasmine 的 Github 的 1.3 分支上找到一个示例 - github.com/pivotal/jasmine/blob/1_3_x/spec/core/SpySpec.js#L183
    【解决方案2】:

    Jasmine 2.0 documentation 描述了 reset() 方法,但 Jasmine 1.3 documentation 没有提及。

    对于 Jasmine 1.3,我相信您正在寻找的是

    foo.setBar.reset();
    

    将 Jasmine 的 2.0 文档翻译成 1.3 语法的等效部分如下:

    it("can be reset", function() {
      foo.setBar(123);
      foo.setBar(456, "baz");
    
      expect(foo.setBar).toHaveBeenCalled();
    
      foo.setBar.reset();
    
      expect(foo.setBar).not.toHaveBeenCalled();
    });
    

    Here's a fiddle as well.

    【讨论】:

      猜你喜欢
      • 2014-03-26
      • 2018-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-09
      • 2017-11-30
      • 1970-01-01
      相关资源
      最近更新 更多