Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stubbing e.preventDefault() in a jasmine test

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();
});
like image 813
Huy Avatar asked Apr 11 '13 05:04

Huy


People also ask

What does the e preventDefault () function do?

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form. Clicking on a link, prevent the link from following the URL.

How do I stop event preventDefault?

We can solve this problem by using the stopPropagation() method because this will prevent the parent from accessing the event. Example 1: HTML.

Do I need e preventDefault?

If you don't use e. preventDefault() , the default behaviour of form submit will fire. It will send browser to the action property of form and browser will disappeared that you don't want it. Save this answer.


2 Answers

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();
like image 148
zbynour Avatar answered Oct 13 '22 00:10

zbynour


You have to pass an object with a field preventDefault that holds your spy:

var event = {preventDefault: jasmine.createSpy()}
this.view.showTopic(event);
expect(event.preventDefault).toHaveBeenCalled
like image 36
Andreas Köberle Avatar answered Oct 12 '22 23:10

Andreas Köberle