0

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.

WingMan20-10
  • 3,594
  • 9
  • 31
  • 42
  • Do you have a larger code sample? – Chris Jan 28 '14 at 18:09
  • code smell,make this an argument of updateElement and it will be testable. the goal of testing is refactoring bad code : http://blog.testdouble.com/posts/2014-01-25-the-failures-of-intro-to-tdd.html – mpm Jan 28 '14 at 18:15

2 Answers2

3

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.

Jordão
  • 55,340
  • 13
  • 112
  • 144
1

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();
Sirko
  • 72,589
  • 19
  • 149
  • 183