jasmine - 如何在分配给 .bind 的函数和对象方法之间进行相等性比较?

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

编辑:我原来的问题没有在 funcToTest 中包含 .bind。这似乎是测试失败的原因。

我正在测试一种方法,该方法将函数分配给对象的 属性。

我想验证新创建的 属性 是否等于函数。 toBetoEqual 都无法通过测试。

这种情况下的最佳做法是什么?

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.`
    })
})

另请注意 - 如果我删除 .bind(this),它会正常工作。

通过将我的 .bind 声明移至构造函数来解决此问题。

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

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

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