Skip to content

Instantly share code, notes, and snippets.

@jackysee
Last active December 25, 2015 18:39
Show Gist options
  • Save jackysee/7021904 to your computer and use it in GitHub Desktop.
Save jackysee/7021904 to your computer and use it in GitHub Desktop.
A handy utility to add stubbed property on obj, it will be cleaned up automatically. One of the use case is require.js module where it shares a global instance.
/**
* Usage:
* describe("someModule", function(){
* beforeEach(function(){
* stubProp(someGlobal, {myVar:'test'});
* });
* });
*
* - stubProp(obj, {myVar:'value'});
* - stubProp(obj, 'myVar', 'myValue');
* */
(function(){
function getValueMap(name, value){
var valueMap = name;
if(typeof name === 'string'){
valueMap = {};
valueMap[name] = value;
}
return valueMap;
}
var bin = [];
function addToBin(obj, name){
bin.push({obj:obj, name:name});
}
this.stubProp = function(obj, name, value){
var valueMap = getValueMap(name, value);
for(var key in valueMap){
if(valueMap.hasOwnProperty(key)){
obj[key] = valueMap[key];
addToBin(obj, key);
}
}
};
afterEach(function(){
for(var i=0; i<bin.length; i++){
var entry = bin[i];
delete entry.obj[entry.name];
}
bin = [];
});
})(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment