问题描述
我正在尝试存储组件方法以进行测试:
I'm trying to stub a React component method for testing purpose:
var Comp = React.createClass({
displayName: "Comp",
plop: function() {
console.log("plop");
},
render: function() {
this.plop();
return React.DOM.div(null, "foo");
}
});
var stub = sinon.stub(Comp.type.prototype, "plop");
React.addons.TestUtils.renderIntoDocument(Comp());
sinon.assert.called(stub); // throws
这很遗憾地将plop打印到控制台上...并且断言失败。
This sadly keeps printing "plop" onto the console… and the assertion fails.
注意:直接存根spec对象方法有效,但是你必须单独导出组件构造函数和规范,以便它们在测试中都可用...而且,你会在创建组件类之前需要存根规范;不太方便:
Note: Directly stubbing the spec object method works, but then you have to export the component constructor and the spec separately so they're both available in tests… Also, you'd need to stub the spec before even creating the component class; not so convenient:
var CompSpec = {
displayName: "Comp",
plop: function() {
console.log("plop");
},
render: function() {
this.plop();
return React.DOM.div("foo");
}
};
var stub = sinon.stub(CompSpec, "plop");
var Comp = React.createClass(CompSpec);
React.addons.TestUtils.renderIntoDocument(Comp());
// plop() is properly stubbed, so you can
sinon.assert.called(stub); // pass
您能想到另一种轻松存根React组件方法的策略吗?
Can you think of another strategy to easily stub a React component method?
推荐答案
你正在对抗React的,缓存 .bind(this)
,这是缠绕你的类方法。您可以通过在React的 __ reactAutoBindMap
中隐藏方法的缓存版本来使代码工作:
You're running up against React's auto-binding feature, which caches the .bind(this)
which is wrapped around your class methods. You can get your code to work by stubbing the cached version of the method in React's __reactAutoBindMap
:
var Comp = React.createClass({
displayName: "Comp",
plop: function() {
console.log("plop");
},
render: function() {
this.plop();
return React.DOM.div(null, "foo");
}
});
// with older versions of React, you may need to use
// Comp.type.prototype instead of Comp.prototype
var stub = sinon.stub(Comp.prototype.__reactAutoBindMap, "plop"); // <--
React.addons.TestUtils.renderIntoDocument(React.createElement(Comp));
sinon.assert.called(stub); // passes
这篇关于使用Sinon对React组件方法进行存根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!