javascript - 如何处理在 enzyme 测试中包含 dom api 方法的 react ref 方法

标签 javascript unit-testing reactjs enzyme

我有一个调用 prop 方法的 react 组件 onSizeChangeonRef叫做。
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/

相关文章:

javascript - 组织的用户限制

javascript - 如何从 URL 获取 GET 查询?

javascript - React 中的 Socket.IO 连接导致持续重新加载

javascript - 如何在 nativescript 中定义默认的 TabView?

javascript - 没有从对象中获取数组

unit-testing - 当使用返回流的存储库对 View 模型进行单元测试时,将其转换为实时数据时会发生错误

java - 单元测试 JAX-RS Controller 的最佳方法?

c# - 带有 Action /函数参数的接口(interface)的最小起订量设置

javascript - React 卸载 30k+ 组件很慢

javascript - 使用 Jest-expo 测试异步存储的示例用例?