ConfusedCoder
ConfusedCoder

Reputation: 103

Stubbing event property in Jasmine Test

I am very new to writing Jasmine test and need some help.

Basically, I have a function below which calls another function and passes the event handler (so basically when a link is clicked on the page the reference of the event is passed to another function so that I could retrieve the content from innerText property of the event):

$('$clickME').click(function (e) {
    return self.CallAnotherFunction(e);
});

function CallAnotherFunction(myevent)
{
    myevent.preventDefault();
    var source = myevent.target || myevent.srcElement;
}

Now in my jasmine test:

it('should read the clicked item text', function ()
{      
    var event = { preventDefault: jasmine.createSpy() };

   //event.source.innerText = "ff";

    //Act
    myObject.prototype.CallAnotherFunction(event);

});

The problem is when I run the test it fails with the below error:

TypeError: 'undefined' is not an object (evaluating 'source.innerText')

Hence it looks like the spy event that I created has a null source.

My Question is how can I set the event.target & event.srcElement on the spy event so that my test can pass.

Thank you

Upvotes: 1

Views: 4607

Answers (1)

ConfusedCoder
ConfusedCoder

Reputation: 103

Found the solution to the above:

A stub set up on the spy is required because using createSpy creates a new mock object. Hence adding the following to set up the spy works like a charm:

    var event = { preventDefault: jasmine.createSpy(), srcElement: jasmine.createSpy() };
    event.srcElement.innerText = 'some value of anchor tag';

Upvotes: 4

Related Questions