Domanda

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.

È stato utile?

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

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top