Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
149
rated 0 times [  153] [ 4]  / answers: 1 / hits: 22590  / 13 Years ago, thu, december 15, 2011, 12:00:00

I'm trying to get better at unit testing my JavaScript. I have the following code:



var categoryVal = $('#category').val();
if (categoryVal === '') {
doSomething();
}


My test runner doesn't have the #category input on the page, so how would I stub/mock out the jQuery selector here? I've looked at both the jasmin and sinon documentation, but can't figure out how to get them to work here, since their stubs operate on objects, which $ is not.


More From » jquery

 Answers
9

The problem here is that $() is a function that returns an object with the method val(). So you have to stub $() to return a stubbed object having the method val.



$ = sinon.stub();
$.withArgs('#category').returns(sinon.stub({val: function(){}}));


But the main mistake here is to let the code you want to test call the function $() to create new instances. Why? Its best practice to create no new instances in your class, but to pass them into the constructor. Let's say you have function that will get a value out of an input, double it, and write it back to another:



function doubleIt(){
$('#el2').val(('#el1').val() *2);
}


In this case you create 2 new objects by calling $(). Now you have to stub $() to return a mock and a stub. Using the next example you can avoid this:



function doubleIt(el1, el2){
el2.val(el1.val() *2);
}


While, in the first case you have to stub $ to return a stub, in the second case you can easily pass a stub and a spy into your function.



So the sinon test for the second one would look like this:



var el1 =  sinon.stub({val: function(){}});
el1.returns(2);

var el2 = sinon.spy({val: function(){}}, 'val')

doubleIt(el1, el2)

assert(el2.withArgs(4).calledOnce)


So, as you have no dom elements here, you can simply test your application logic with no need to create the same dom as in your app.


[#88539] Wednesday, December 14, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brynnleslis

Total Points: 425
Total Questions: 100
Total Answers: 115

Location: Wallis and Futuna
Member since Tue, Mar 30, 2021
3 Years ago
brynnleslis questions
Sun, Nov 28, 21, 00:00, 3 Years ago
Tue, Jun 29, 21, 00:00, 3 Years ago
Fri, Feb 19, 21, 00:00, 3 Years ago
Wed, Jul 8, 20, 00:00, 4 Years ago
Tue, May 19, 20, 00:00, 4 Years ago
;