Reputation: 11206
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();
});
Upvotes: 11
Views: 20466
Reputation: 3458
This is very similar to approaches on top. I just mocked out the event and passed preventDefault with an sinon spy. The difference was that I had to identify the type which was a click on my test.
var e = {
type: 'click',
preventDefault: sinon.spy()
};
Upvotes: 0
Reputation: 21
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 :-) !!!!!
Upvotes: 2
Reputation: 19817
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();
Upvotes: 28
Reputation: 110892
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
Upvotes: 1