Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Allow spies to be overriden #160

Closed
mcmire opened this Issue · 3 comments

2 participants

Elliot Winkler Rajan Agaskar
Elliot Winkler

Right now if you spy on a method more than once, Jasmine will complain. I would like it so that Jasmine did not do this. The use case is that I would like set up a default spy in my beforeEach block (as most tests in the test group depend on this) and then override this spy for individual tests where behavior differs from the default. Like so:

describe '#method', ->
  beforeEach ->
    spyOn(http, 'request').andCallFake (fn) -> fn()

  it 'should do something on success', ->
    # some test here
    foo.method()

  it 'should do something else assuming success', ->
    # some test here
    foo.method()

  it 'should do yet another thing assuming success', ->
    # some test here
    foo.method()

  it 'should do a different thing on error', ->
    error = new Error('oh noes')
    spyOn(http, 'request').andCallFake (fn) -> fn(error)
    fn = jasmine.createSpy()
    foo.method(fn)
    expect(fn).toHaveBeenCalledWith(error)

This is obviously a contrived example; a better example would be if the method is more complicated and I am setting up more things in my beforeEach (and have more tests). You can see how this might be useful.

WDYT?

Elliot Winkler

Also I realize this is a dupe of #32 but I feel this feature should exist. Why would you want to prevent a spy from being defined twice -- is it just for a sanity check?

Another example is

describe '#method', ->
  beforeEach, ->
    spyOn(some, 'method')

  it 'should do whatever', ->
    # a test that calls some.method but requires that it not
    # actually be called -- maybe it makes a request

  it 'should do something else', ->
    spyOn(some, 'method').andCallThrough()
    # call some.method multiple times.........
    expect(some.method.callCount).toBe(3)
Rajan Agaskar
Owner

You can get this behavior by doing the following:

describe '#method', ->
 beforeEach ->
   spyOn(http, 'request').andCallFake (fn) -> fn()

 it 'should do a different thing on error', ->
   error = new Error('oh noes')
   http.request.andCallFake (fn) -> fn(error)
   fn = jasmine.createSpy()
   foo.method(fn)
   expect(fn).toHaveBeenCalledWith(error)

IE, you can change the spies behavior by calling these methods on the spy itself instead of creating yet another spy instance.

As you are able to change the spy's behavior through this syntax, I don't see any value in adding nested Spies (which may add further complexity to Jasmine).

Rajan Agaskar ragaskar closed this
Elliot Winkler

Ah. Okay, that didn't occur to me before but it makes sense now that I look at it. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.