Stubbing e.preventDefault() in a jasmine test

15,597

Solution 1

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();

Solution 2

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

Solution 3

don't know this approach is correct or not but works for me, feel free to tell if it is not a good approach

step1:create a eventStub with the function for prevent default

 const eventStub = {
      preventDeafult() {}
    }

step2: write the 'it' Block:

it('should preventDefault when dragover event occurs', () => {
  // step 3 goes here
  // step 4 goes here
  // step 5 goes here
});

step3:create spy for prevent default:

const spy = spyOn(eventStub, 'preventDefault');

step4:trigger the event let's say dragover and pass the eventStub

  component.triggerEventHandler('dragover', eventStub)

step5:write the assertion

expect(spy).tohaveBeenCalled()

Note: "component" in step 4 is the instance of component we get from fixture Example to get component instance from fixture:

let fixture = TestBed.createComponent(<your Component's Class Name>);
let component = fixture.componentInstance;

try and let me know if it works for you thanks you,,,, Happyyy coding :-) !!!!!

Share:
15,597
Huy
Author by

Huy

Making it rain stackoverflow points errday

Updated on June 09, 2022

Comments

  • Huy
    Huy about 2 years

    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();
    });