Providing a third-party library is dangerous because the environments it's used in can vary quite a lot. Talking about JS run in a browser, accidentally overwriting a global (i.e. window
) property, which is possibly used by another library, can break sites that rely heavily on scripts.
To avoid that, I'd like to automatically test if the global scope was modified in any unintended way, such as:
function foo() {
myVar = 'this becomes global because of a missing var keyword';
}
window.jQuery = 'this is not jQuery at all, breaking everything that uses it';
(Am I missing another variant?)
A typical example
My library packages a specific version of jQuery. Using var myJQuery = jQuery.noConflict(true);
, I can restore a pre-existing $
and jQuery
. If I forget to supply true
as a parameter, only $
is restored, and my version of jQuery remains in window.jQuery
, possibly breaking other libraries that require a different version.
I'd like to have a test that can detect such a scenario automatically.
What I tried so far
Static analysis with JSLint/JSHint
As far as I can tell, this only covers accidental globals due to the missing var
keyword. "Intentional" window
property assignments can not be detected, apparently.
There is JSHint's global
configuration option, which allows me to specify whether a global property can be written to, but in that case, wouldn't I have to list all possible (or realistic) accidental globals I might encounter in the future?
Would be implementing a custom check looking for window.something = ...
assignments a good idea?
Comparing window
after a Jasmine spec with a snapshot of the window
from before the spec
Since I have an extensive suite of Jasmine tests, making a snapshot of window
before each spec, and comparing the current window
with that snapshot after the spec was executed seemed like a good idea. The big advantage is that it covers many paths of execution. For a variety of reasons related to some legacy code, that didn't work out without major refactoring, which would take more time than I have.
Same as the above, but manually
That somewhat works, but it covers hardly any paths of execution, possibly leaving some cases of leaked globals undetected.
Taking care that the global scope is not modified during development
I could hardly find resources about automatically testing such a scenario, so it looks like most people are just careful to always use var
, scope everything, and, if it's absolutely necessary, use as few globals as possible with very unique names. Maybe they also have the strategy to let if fail and roll back quickly once users start to complain.
This approach is not really satisfying as it lacks the rigor of automatic testing.
tl;dr What I want to find out
- Is there an existing way to automatically test for global scope pollution?
- If not, what's the best way to do that in terms of thoroughness and required implementation effort?
Aucun commentaire:
Enregistrer un commentaire