Stubbing e.preventDefault() in a jasmine test

jasmine, javascript

Solution

Another way to create mock object (with spies you need) is to use `jasmine.createSpyObj()`. Array containing spy names have to be passed as second parameter.

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

Problem

I recently added an `e.preventDefault()` to one of my javascript functions and it broke my jasmine spec. I've tried `spyOn(e, 'preventDefault').andReturn(true);` but I get `e` is undefined error. How do I stub `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(); }); ```

Original source