How can I test for equality to a bound function when unit testing?
Instead of
expect(bar.register.calls.argsFor(0)[0]).toEqual(bar.handler);
you can do
expect(Object.create(bar.handler.prototype) instanceof bar.register.calls.argsFor(0)[0])
.toBe(true);
or
expect(Object.create(bar.handler.prototype)).
toEqual(jasmine.any(bar.register.calls.argsFor(0)[0]));
This works because the internal [[HasInstance]]
method of the bound function delegates to the [[HasInstance]]
method of the original function.
This blog post has a more detailed analysis of bound functions.
this.handler.bind(this)
creates completely a new function, therefore it is not equal to bar.handler
.
See Function.prototype.bind().
You can pass bounded function as argument to your initialize
function and then test it, e.g.:
var handler = bar.handler.bind(bar);
bar.initialize(handler);
expect(bar.register.calls.argsFor(0)[0]).toEqual(handler);