How to manually delete/destroy a spy?

4,371 views
Skip to first unread message

Tanguy Krotoff

unread,
Feb 20, 2017, 12:10:36 PM2/20/17
to Jasmine
Hi all,

How to manually delete/destroy a spy?

Example:

function signIn(done) {
  ...
  // Fails the 2x time with "<spyOn> : bar has already been spied upon"
  spyOn(foo, 'bar').and.callThrough();
  ...
  expect(foo.bar).toHaveBeenCalledTimes(1);
}

function signOut(done) {
  ...
}

it('should be able to sign-in/sign-out multiple times', done => {
  signIn(() => {
    signOut(() => {
      signIn(() => { // Fails with "<spyOn> : bar has already been spied upon"
        done();
      });
    });
  });
});


- Currently the second signIn call fails with "<spyOn> : bar has already been spied upon"
- I cannot make spyOn global otherwise error "Spies must be created in a before function or a spec"

So I would like to be able to write something like this:

function signIn(done) {
  ...
  const spy = spyOn(foo, 'bar').and.callThrough();
  ...
  expect(foo.bar).toHaveBeenCalledTimes(1);
  spy.destroy();
}


Any idea?

Tim Wright

unread,
Feb 21, 2017, 4:11:14 AM2/21/17
to jasmi...@googlegroups.com

Hi Tanguy,

Have you tried putting the spy creation in a beforeEach block? Sort of like this:

beforeEach(()=> {
  spyOn(foo, 'bar').and.callThrough();
})

Tim

--
You received this message because you are subscribed to the Google Groups "Jasmine" group.
To unsubscribe from this group and stop receiving emails from it, send an email to jasmine-js+unsubscribe@googlegroups.com.
To post to this group, send email to jasmi...@googlegroups.com.
Visit this group at https://groups.google.com/group/jasmine-js.
For more options, visit https://groups.google.com/d/optout.

Tanguy Krotoff

unread,
Feb 21, 2017, 6:05:16 AM2/21/17
to Jasmine
Problems with your proposal:
- non-blocking issue: the spy becomes global instead of local to signIn()
- blocking issue:
  expect(foo.bar).toHaveBeenCalledTimes(1) will fail with the second signIn call because foo.bar has then been called 2 times:

it('should be able to sign-in/sign-out multiple times', done => {
  signIn(() => { // expect(foo.bar).toHaveBeenCalledTimes(1)
    signOut(() => {
      signIn(() => { // expect(foo.bar).toHaveBeenCalledTimes(2)
        done();
      });
    });
  });
});


Just to clear things up: signIn, signOut... are bricks (i.e simple functions - not Jasmine tests) that are reused to write complex Jasmine test scenarios like:
- signIn, doSomething1, signOut
- signIn, doSomething1, doSomething2, doSomething3, signOut
- signIn, signOut, signIn, signOut, signIn, signOut
- ...
To unsubscribe from this group and stop receiving emails from it, send an email to jasmine-js+...@googlegroups.com.

Tanguy Krotoff

unread,
Feb 24, 2017, 4:56:14 AM2/24/17
to Jasmine
I think my usecase is valid so I've opened a feature request on GitHub: https://github.com/jasmine/jasmine/issues/1281
Reply all
Reply to author
Forward
0 new messages