【发布时间】:2017-10-17 07:30:35
【问题描述】:
我有一个反应组件,它在调用 onRef 时调用 prop 方法 onSizeChange。
onRef 包含一个 dom api 查询。
我想断言 onSizeChange 被调用。这在酶的安装中失败,因为 getBBox() 在 jsdom 中不存在。错误:getBBox is not a function
如何让测试运行,以便断言 onSizeChange 被调用?
更广泛的问题:您如何处理 ref 函数中的 dom api 查询,当测试像在 jsdom 中一样运行时不受支持,它们可以以某种方式模拟吗?
/* Abbreviated component class code */
onRef(textNode){
if(!textNode){
return;
}
const { onSizeChange } = this.props;
const { width, height } = textNode.getBBox();
onSizeChange({ width, height });
}
render(){
return (
<svg>
<text
ref={textNode => this.onRef(textNode)}
x="50%"
y="50%"
alignmentBaseline="middle"
textAnchor="middle"
stroke="none">
some text
</text>
</svg>
);
}
酶测试:
it('should call onSizeChange handler on render', () => {
const props = {
onSizeChange: () => {}
};
const spy = sinon.spy(props, 'onSizeChange');
const wrapper = mount(<NodeLabel {...props} />);
expect(spy.called).to.equal(true);
spy.restore();
});
【问题讨论】:
标签: javascript unit-testing reactjs enzyme