我有一个react组件,在调用onSizeChange
时调用prop方法onRef
。
onRef
包含一个dom api查询。
我想断言onSizeChange被调用。这在酶的安装中失败,因为jsdom中不存在getBBox()。错误: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();
});
我自己没有解决这个问题,直到我发现这个方法使用了here:
关于它的好处是没有必要摆弄jsdom本身,你只需用getBBox
覆盖beforeEach/afterEach
的原型:
const originalGetBBox = SVGElement.prototype.getBBox;
beforeEach(() => SVGElement.prototype.getBBox = () => {
return {<insert your mock data for bbox here>};
});
afterEach(() => (SVGElement.prototype.getBBox = originalGetBBox));