如何处理在酶测试中含有dom api方法的反应方法

问题描述 投票:2回答:1

我有一个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();
});
javascript unit-testing reactjs enzyme
1个回答
0
投票

我自己没有解决这个问题,直到我发现这个方法使用了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));
© www.soinside.com 2019 - 2024. All rights reserved.