jasmine-jquery icon indicating copy to clipboard operation
jasmine-jquery copied to clipboard

EventSpy handler is not removed after each test

Open patricknixon opened this issue 9 years ago • 4 comments

Every time an event spy is created (e.g. in beforeEach block), a new event handler is added to the selected element. If that element persists between tests, multiple spy handlers will be attached, causing the call count to increase arithmetically. For example, the second test below fails even though it is identical to the first one:

var eventSpy;

beforeEach(function() {
  eventSpy = spyOnEvent(document, 'myEvent');
});

it('test 1', function() {
  expect(eventSpy.calls.count()).toBe(0);
  $(document).trigger('myEvent');
  expect(eventSpy.calls.count()).toBe(1);
});

it('test 2', function() {
  expect(eventSpy.calls.count()).toBe(0);
  $(document).trigger('myEvent');
  expect(eventSpy.calls.count()).toBe(1);
});

patricknixon avatar Apr 13 '15 21:04 patricknixon

I think the addition of this will help:

afterEach(function() {
    $(document).off();
});

jasmine-jquery does not, from what I can see, unregister listeners. A possible assumption here is the element one attaches an event spy too, should be destroyed between tests.

The reason why the call count is magically incrementing is because the document element is not replaced between tests.

renegare avatar Jul 20 '15 10:07 renegare

@renegare Yes that is correct and that's exactly what I consider a bug. Spies should be removed between tests.

patricknixon avatar Jul 20 '15 14:07 patricknixon

I understand where you are coming from. Had me stomped. The reason I choose not to refer to this as bug because I looked at the code behind this, its quite intentional and IMO makes sense within the context of testing ...

Any who, saying this, I use FlightJS (jasmine-flight) so elements are destroyed automatically, so would be nice and would save time "bug hunting" if all spies are automatically cleaned up.

I think its best someone from the core dev team give some insight on this.

renegare avatar Jul 20 '15 15:07 renegare

Just ran into this issue today, annoying.

dmail avatar Dec 12 '17 13:12 dmail