When writing unit tests for my functions, I encountered an issue with a bound function in the test runner. The problem arose when trying to bind a function to have reference to 'this' inside an inner function. Here is the code snippet in question:
loadStates: function(name, stateName, options) {
if (myModule.getModule(name) !== undefined) {
this.prepState(name, stateName, options);
} else {
var bindForCheck = this.prepState.bind(this);
//module cannot be found check for 5 seconds
$log.warn("Requesting " + name + "...");
var timeToCheck = true;
setTimeout(function() {
timeToCheck = false;
}, 5000);
var check = {
init: function() {
check.checkAgain();
},
checkAgain: function() {
if (timeToCheck) {
if (myModule.getModule(name) !== undefined) {
bindForCheck(name, stateName, options);
} else {
//still doesn't exist
setTimeout(check.checkAgain, 200);
}
} else {
//doesn't exist after 5 seconds
$log.error("Requested module (" + name + ") could not be found at this time.");
}
}
};
check.init();
}
}
The specific issue occurs with the line:
var bindForCheck = this.prepState.bind(this);
This line allows me to call an outer function within the check.checkAgain() function.
When I try to run the else section of the function, the test runner throws the following error:
TypeError: 'undefined' is not a function (evaluating 'this.prepState.bind(this)')
I am seeking assistance to resolve this issue as I'm currently stuck on how to fix it. Any help would be greatly appreciated. Thank you!