How can I check the equality of a related function in unit testing?

I want to check that the argument passed to the function is a function reference, but the function reference is passed using bind().

Consider this code that needs to be checked (shortened for brevity):

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

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

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

The argument does not match the function reference that I assume due to the associated function with bind()- how can I verify that the correct function reference is passed when using the method bind()on it?

Note. This does not apply to jasmine, I just thought it was appropriate because of the methods used.

+4
3

expect(bar.register.calls.argsFor(0)[0]).toEqual(bar.handler);

expect(Object.create(bar.handler.prototype) instanceof bar.register.calls.argsFor(0)[0])
  .toBe(true);

expect(Object.create(bar.handler.prototype)).
  toEqual(jasmine.any(bar.register.calls.argsFor(0)[0]));

, [[HasInstance]] [[HasInstance]] .

.

+4

this.handler.bind(this) , bar.handler. . Function.prototype.bind().

initialize, , :

var handler = bar.handler.bind(bar);
bar.initialize(handler);
expect(bar.register.calls.argsFor(0)[0]).toEqual(handler);
+1

.

anon func, register - , , .

it('register handler', function () {
    spyOn(bar, 'handler').and.callFake(function(){}); // do nothing
    spyOn(bar, 'register').and.callFake(function(fn){
        fn();
        expect(bar.handler).toHaveBeenCalled();
    });
    bar.initialize();
});
+1

Source: https://habr.com/ru/post/1620293/


All Articles