Hi guys I need to test if a jquery script like the below one contains a given function (for example foo):
$( document ).ready( function() {
let n = 5;
function foo() {
console.log(n * 2)
}
foo();
})
I tried this function to test whether is function or not:
function isFunction(x) {return Object.prototype.toString.call(x) === '[object Function]'}
but it didn't because of the closure and eventually, I end up with a function not defined error.
CodePudding user response:
What about something like this. Granted this is pretty outside-the-box thinking and will become broken if you change the name of the foo() function ever.
function readyCallback(){
let n = 5;
function foo() {
console.log(n * 2)
}
foo();
}
$( document ).ready(readyCallback);
const testBoolean = readyCallback.toString().includes('function foo()');
console.log(testBoolean ? "The Test Has Passed" : 'The Test Has Failed')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>