Skip to content

Instantly share code, notes, and snippets.

@davyboyhayes
Created July 1, 2015 10:11
Show Gist options
  • Save davyboyhayes/8cc65c91664548b43bb7 to your computer and use it in GitHub Desktop.
Save davyboyhayes/8cc65c91664548b43bb7 to your computer and use it in GitHub Desktop.
(function(jasmine){
var protectedVariables = {};
var oldJasmineIt = it;
/**
* This should be used to protect and tear down any variables inside a test class (not a beforeEach/afterEach function)
* that you would typically store, then reset back to the stored values. It helps to reduce some noise in tests
* @param protectedList
*/
jasmine.protect = function(protectedList, fn) {
if (typeof protectedList.length !== 'number') {
throw new Error("Protected List wasn't an array");
}
var caller = findProtectedFunctionCaller(fn || jasmine.protect.caller);
var protectedForFunction = protectedVariables[caller];
if (!protectedForFunction) {
protectedVariables[caller] = protectedForFunction = [];
}
for (var i = 0; i < protectedList.length; i++) {
var protectObject = protectedList[i];
var protectedParent = protectObject[0];
var protectedName = protectObject[1];
var protectedValue = protectedParent[protectedName];
protectedForFunction.push({
protectedParent: protectedParent,
protectedName: protectedName,
protectedValue: protectedValue
});
}
};
var findProtectedFunctionCaller = function(fn) {
var returnFn = fn;
while (returnFn && typeof returnFn.__protectable === 'undefined') {
returnFn = returnFn.caller;
}
return returnFn || fn;
};
jasmine.protectAndSet = function(parentObject, name, newValue) {
jasmine.protect([[parentObject, name]], jasmine.protectAndSet.caller);
parentObject[name] = newValue;
};
jasmine.unprotect = function(fn) {
var caller = findProtectedFunctionCaller(fn || jasmine.unprotect.caller);
var protectedForFunction = protectedVariables[caller];
if (protectedForFunction) {
for (var i = protectedForFunction.length - 1; i >= 0; i--) {
var protectedObject = protectedForFunction[i];
protectedObject.protectedParent[protectedObject.protectedName] = protectedObject.protectedValue;
}
}
protectedVariables[caller] = undefined;
};
// Automatically override the it, so that this automatically cleans up after itself
it = function(describe, fn) {
var runAndCleanUp = function() {
fn.apply(this,arguments);
jasmine.unprotect(runAndCleanUp);
};
runAndCleanUp.__protectable = true;
oldJasmineIt(describe, runAndCleanUp);
}
})(jasmine);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment