In C you can use #ifdef to tell the compiler to ignore certain parts of the code, depending on build-time configuration or environmental factors like operating system features.
I've used a similar pattern in JavaScript, and we can think of this in the same way.
// Some code only needs to be run in the browser, and
// I don't really care about testing it.
if (typeof document === 'object') {
$(document).ready(function() {
$.getJSON('/json/all/').done(function(items) {
var search = new Search(items);
}
}
}
// And some code only needs to be run in node.js, so
// my tests can connect to it.
if (typeof module !== 'undefined') {
module.exports = { Search: Search };
}
This makes the code more flexible. But I would only use this to stub out entire functions, not inside parts of logic. That would make the code more complicated and confusing.