Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test for equality to a bound function when unit testing?

I want to test that an argument passed to a function is a function reference but the function reference is being passed using bind().

Consider this code which is to be tested (shortened for brevity):

initialize: function () {
    this.register(this.handler.bind(this));
}

And this unit test to check if register() was called with handler():

it('register handler', function () {
    spyOn(bar, 'register');
    bar.initialize();
    expect(bar.register.calls.argsFor(0)[0]).toEqual(bar.handler);
});

The arg doesn't equal the function reference I guess due to the bound function using bind() - how can I test that the correct function reference is being passed while still using the bind() method on it?

Note: This isn't specific to jasmine, I just thought it was appropriate because of the methods being used.

like image 478
Phil Cooper Avatar asked Dec 16 '15 09:12

Phil Cooper


1 Answers

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.

like image 133
user5325596 Avatar answered Oct 22 '22 16:10

user5325596