David Ziemann
David Ziemann

Reputation: 970

Reusing Jasmine Spy with different andCallFake() method

I am attempting to write some advanced tests in jasmine (version 1.3) where I am setting up a spy on the $.getJSON() method. This is being set up in the beforeEach block seen here:

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

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

I then go through the search query as usual (which works just fine).

In one of my later tests, I have a second API that is pinged. I would like to change the response that is being sent, but can't seem to get anything to work. This Blog seems to imply that I could just reuse the spy with a different andCallFake(), but it does not seem to be working. I get the original response object rather than my overridden method

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

Any thoughts on how I could reuse or destroy the original spy on method?

Upvotes: 4

Views: 2359

Answers (2)

The DIMM Reaper
The DIMM Reaper

Reputation: 3708

The Jasmine 2.0 documentation describes the reset() method, but the Jasmine 1.3 documentation does not mention it.

For Jasmine 1.3, I believe what you're looking for is

foo.setBar.reset();

The equivalent portion of Jasmine's 2.0 documentation translated into 1.3 syntax would be as follows:

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.

Upvotes: 2

Eitan Peer
Eitan Peer

Reputation: 4345

You can reset the spy.

From 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);
});

Upvotes: 3

Related Questions