Question

Why does the same test case, when run a second time, fail?

Setup

var element, elementClickSpy;
beforeEach(function() {
    element = angular.element('<div id="some-element"></div>');
    $('body').append(element);
    elementClickSpy = spyOnEvent('#some-element', 'click');
});

Case 1

The first case works as expected.

it('should work', function() {
    expect(elementClickSpy).not.toHaveBeenTriggered();
    element.click();
    expect(elementClickSpy).toHaveBeenTriggered();
});

Case 2 (Identical to Case 1)

The second assertion fails for some reason even though the case is an exact copy of the first case.

it('should work again', function() {
    expect(elementClickSpy).not.toHaveBeenTriggered();
    element.click();
    expect(elementClickSpy).toHaveBeenTriggered();
});
Was it helpful?

Solution

To summarize what we found in the comments above, it seems as though the DOM isn't getting cleaned up between tests. Because you're using an ID #some-element to bind to the click handler, the second test is spying on the first element, but you're clicking on the new one.

You can either:

  1. Spy on exactly the element you're concerned with: spyOnEvent(element, 'click') or
  2. Clean up the DOM between tests (by .remove()ing the button, or clearing the body's HTML)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top