Question

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.

Was it helpful?

Solution 2

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top