Reputation: 3744
if i have a Javascript function that uses, something like this...$(this)[0].element.id;
updateElement(){
$(this)[0].element.id;
}
I am using Qunit, is there a way i can mock 'this'
I would like to be able to test this function.
Upvotes: 0
Views: 375
Reputation: 56537
With the functions apply
or call
of the Function
object, you can change the value of this
when calling a function:
var mock = ...
updateElement.call(mock);
this
will refer to mock
inside the updateElement
call above.
Upvotes: 3
Reputation: 74086
I assume, that this
refers to some jQuery Object. You could create the respective objects using the jQuery function and then use bind()
to attach the object as this
to your actual function:
// prepare the DOM objects
var $elem = $( '...' );
// prepare a bound function
var boundFct = updateElement.bind( $elem );
// execute your function
boundFct();
Upvotes: 1