【问题标题】:how to handle react ref methods which contain dom api methods in enzyme tests如何处理在酶测试中包含 dom api 方法的 react ref 方法
【发布时间】: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


    【解决方案1】:

    在找到使用here的方法之前,我自己没能解决这个问题:

    它的好处是不需要摆弄 jsdom 本身,你只需使用 beforeEach/afterEach 覆盖 getBBox 的原型:

    const originalGetBBox = SVGElement.prototype.getBBox;
    beforeEach(() => SVGElement.prototype.getBBox = () => {
      return {<insert your mock data for bbox here>};
    });
    afterEach(() => (SVGElement.prototype.getBBox = originalGetBBox));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-13
      • 2019-11-12
      • 2020-09-24
      • 2017-07-03
      • 1970-01-01
      • 2018-06-21
      • 1970-01-01
      • 2019-03-23
      相关资源
      最近更新 更多