Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jasmine - How to do equality comparison between function and object method assigned with .bind?

Edit: My original question did not include .bind in funcToTest. That appears to be what's failing the test.

I am testing a method that assigns a function to an object's property.

I want to verify that the newly created property equals the function. Neither toBe nor toEqual are getting the test to pass.

What's best practice in this case?

class TestClass {
    constructor() {
    }

    initMyObj() {
        this.myObj = {
            func: this.myFunc.bind(this) //it works fine without .bind
        }
    }

    funcToTest() {
        console.log('Thanks for reading!');
    }
}


describe('TestClass', function() {
    beforeEach(function() {
        this.test = new TestClass();
    });
    it('should set "myObj.func" property to funcToTest method', function() {
        this.test.initMyObj();
        expect(this.test.myObj.func).toBe(this.test.funcToTest); //fails with `Expected Function to be Function.`
        expect(this.test.myObj.func).toEqual(this.test.funcToTest); //fails with `Expected Function to equal Function.`
    })
})

Also note - if I remove .bind(this), it works fine.

like image 812
user2954463 Avatar asked Mar 02 '26 15:03

user2954463


1 Answers

Solved this by moving my .bind declaration to the constructor.

class TestClass {
    constructor() {
        this.myFunc = this.myFunc.bind(this)
    }

    initMyObj() {
        this.myObj = {
            func: this.myFunc
        }
    }

    funcToTest() {
        console.log('Thanks for reading!');
    }
}
like image 146
user2954463 Avatar answered Mar 05 '26 04:03

user2954463



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!