It occurred to me that it might be possible to test private functions in javascript by parsing the source code, and injecting some code to expose private functions globally...
source to test
function greeting(seedin){
// this function is private, so can't be reached by tests...
function chooseRandom(list, seed){ return list[Math.floor(seed*list.length)]; }
return chooseRandom(["Hi there", "Hello", "Greetings..."], seedin);
}
eval based hack to extract private function
What this is doing, is to simply inject a line into the start of the function which returns the required private function, so that executing the original function with eval will instead return the private function...
var chooseRandom = eval('(function(){'+greeting.toString().replace(/(function.+?{)/,'$1\nreturn chooseRandom;')+'; return greeting();'+'}())');
now I can test my private function...
console.log(chooseRandom([1,2,3],0.5) === 2);
my question
Is this a reasonable approach? Are there any libraries/tools out there to achieve similar goal?
Aucun commentaire:
Enregistrer un commentaire