在模块的 create 方法中,我将函数绑定(bind)到变量。
var __ = function() {};
__.create = function() {
var instance = new __();
instance.bound = instance.functionToBindTo.bind(instance, 'boundParameter');
return instance;
}
__.prototype.functionToBindTo = function(paramater1, parameter2) {
//do stuff
}
我现在希望能够测试调用“bound”是否会将“boundParameter”设置为parameter1。
通常我会做类似的事情
'ensure parameter1 passed as first parameter' : function(test) {
var newInstance = ClassToTest.create();
newInstance.functionToBindTo = function(parameter1) {
test.equal(parameter1, 'boundParameter');
};
newInstance.bound();
test.done();
}
但是,由于 .bind() 实际上创建了一个新函数,因此这不起作用,因为我无法在测试中覆盖它。我知道可以使用该选项来滚动我自己的bind2方法并对其进行修补,但我希望有一种方法可以避免这种情况。
有什么想法吗?
谢谢
马特
最佳答案
这可能不是正确的方法,但对于上面的测试用例,您可以覆盖 ClassToTest
原型(prototype)对象中的 functionToBindTo
:
'ensure parameter1 passed as first parameter' : function(test) {
ClassToTest.prototype.functionToBindTo = function(parameter1) {
test.equal(parameter1, 'boundParameter');
};
var newInstance = ClassToTest.create();
newInstance.bound();
test.done();
}
关于javascript - 在 Node 中测试绑定(bind)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31388396/