Stubbing e.preventDefault () in jasmine test

I recently added e.preventDefault() to one of my javascript functions, and it broke my jasmine specification. I tried spyOn(e, 'preventDefault').andReturn(true); but i get e undefined error. How to block e.preventDefault()?

 showTopic: function(e) { e.preventDefault(); midParent.prototype.showTopic.call(this, this.model, popup); this.topic.render(); } it("calls the parent", function() { var parentSpy = spyOn(midParent.prototype, "showTopic"); this.view.topic = { render: function() {} }; this.view.showTopic(); expect(parentSpy).toHaveBeenCalled(); }); 
+6
source share
3 answers

Another way to create a mock object (using the spies you need) is to use jasmine.createSpyObj() . An array containing the names of the spies should be passed as the second parameter.

 var e = jasmine.createSpyObj('e', [ 'preventDefault' ]); this.view.showTopic(e); expect(e.preventDefault).toHaveBeenCalled(); 
+15
source

You need to pass an object with the preventDefault field that contains your spy:

 var event = {preventDefault: jasmine.createSpy()} this.view.showTopic(event); expect(event.preventDefault).toHaveBeenCalled 
+1
source

This is very similar to the approaches from above. I just mocked this event and skipped theDefault with a Sinon spy. The difference was that I had to identify the type that was clicked on my test.

  var e = { type: 'click', preventDefault: sinon.spy() }; 
0
source

All Articles