For the purpose of a unit test, I would like to check if a particular function has been bound.
function foo() {}
var bar = foo.bind(context);
assertBound(bar); // --> true
assertBound(foo); // --> false
Is there someway to check that bar
has been bound that doesn't require mocking the bind
function?
While How to get [[boundthis]] from function is asking about getting the [[boundthis]]
, I am wondering about just checking it has been bound.
{Function}.name
in ES6In ES6 all functions are given a static name
property.
function aFunction () {}
console.log(aFunction.name) // => 'aFunction'
Unnamed functions like arrow functions have an empty string for their name:
var aFunction = function () {}
console.log(aFunction.name) // => ''
Both named and unnamed functions when bound to a context using Function#bind
have their name
preceded with 'bound '
:
// Named function
function aFunction () {}
var boundFunc = aFunction.bind(this)
console.log(boundFunc.name) // => 'bound aFunction'
// Unnamed function
var anotherFunc = function () {} // or `anotherFunc = () => 0`
var anotherBoundFunc = anotherFunc.bind(this)
console.log(anotherBoundFunc.name) // => 'bound '
We can use this to see if a function is bound:
function assertBound (fn) {
return typeof fn == 'function' && fn.name.startsWith('bound ');
}
Note: checking that the word bound has a space after it is important so that we don't catch functions like function boundFunction () {}
, for example.
______
Function#toString
in ES5A hacky way to know if a user-defined function is bound in ES5 is to cast it to a string using Function#toString
and looking for the text '[native code]'
:
function assertBound (fn) {
return typeof fn == 'function' && fn.toString().indexOf('[native code]') > -1;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With