我有一个调用 prop 方法的 react 组件 onSizeChange
当onRef
叫做。onRef
包含一个 dom api 查询。
我想断言 onSizeChange 被调用。这在 enzyme 的安装中失败,因为 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();
});
最佳答案
我自己没能解决这个问题,直到我发现使用的方法 here :
它的好处是没有必要摆弄 jsdom 本身,你只需覆盖 getBBox
的原型(prototype)使用 beforeEach/afterEach
:
const originalGetBBox = SVGElement.prototype.getBBox;
beforeEach(() => SVGElement.prototype.getBBox = () => {
return {<insert your mock data for bbox here>};
});
afterEach(() => (SVGElement.prototype.getBBox = originalGetBBox));
关于javascript - 如何处理在 enzyme 测试中包含 dom api 方法的 react ref 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44031574/