DOM events are used all the time while coding frontend applications, and sometimes we want to write a spec that checks whether an event is being triggered.
An event could be something like a form submission or an input having changed, so how can we use Spies to do that?
We can write a new acceptance criterion to NewInvestmentView
to check that its form is being submitted when the add button is clicked:
describe("and when its add button is clicked", function() { beforeEach(function() { spyOnEvent(view.$el, 'submit'), view.$el.find('input[type=submit]').click(); }); it("should submit the form", function() { expect('submit').toHaveBeenTriggeredOn(view.$el); }); });
To write this spec, we use the spyOnEvent
global function provided by the Jasmine jQuery plugin.
It works by accepting a DOM element (view.$el
) and an event we want to spy on (submit
). Then later on, we can check with toHaveBeenTriggeredOn
whether the event was triggered on the element.