I test selectors manually, then pass them to code that uses them. I can then unit test the code that uses them. If you want to just test a selector, you need access to the HTML it affects. Your test could include HTML to target, something like:
test("selector works", function() {
var html = $('<input type="select"><option value=0/></input');
var result = $('option', html);
ok(result.count() == 1);
});
But I don't do that... I put my selectors at the edge of the code so I can get to them quickly and step through them under the debugger. I'll have a simple class whose properties are those selectors. Then I'll mock/stub that simple class, so I can write code for everything dependent on those selectors.
The reason I don't test my selectors is because the HTML they target is generated by ASP.NET code, and hard to get to from a javascript test. But I can wrap them in a Humble Object ("http://xunitpatterns.com/Humble Object.html") then test code that depends on that humble object. Here's a simple wrapper class that I can replace with test doubles:
var createSelectWidget = function(rootSelector)
{
return {
userText : $('span', rootSelector),
inputList : $('option', rootSelector),
};
}
Whatever dependency injection pattern you use, you can then stub it like below. Suppose my widget has a select input to read the value of, and a span I want to write some results to:
var createSelectWidgetStub = function()
{
return {
userText : { text = function() {}},
inputList : { val = function() {}},
};
}
I can then pass around this stub in tests where I want to isolate the dependency but don't care about interactions with that dependency. When I want to verify interactions with the dependency, I can mock it with JSMock. Suppose I want to verify interactions with the input list, I would prepare a stub with the one element mock'd:
var selectMock = createSelectWidgetStub();
selectMock.inputList = mc.createMock(selectMock.inputList);