【问题标题】:Does react-virtualized work with airbnb/enzyme?react-virtualized 是否适用于 airbnb/enzyme?
【发布时间】:2016-10-14 12:52:13
【问题描述】:

是否可以同时使用 react-virtualized 和酶?当我尝试将它们一起使用时,我似乎在网格中得到了一个空的项目列表。

【问题讨论】:

  • 您确定将宽度和高度 > 0 传递给网格吗? (你有机会分享一些代码吗?)
  • 让我做一个简化的例子。
  • 我认为问题在于我正在使用 Autosizer。将继续调查...
  • 没问题。我将添加一个“答案”,以便格式化一些示例代码。

标签: react-virtualized


【解决方案1】:

两者应该一起工作,是的。我认为可能的问题是 react-virtualized 组件的宽度或高度为 0,这导致它不渲染任何东西。 (它只渲染到足以填满它所拥有的“窗口”。)

假设您使用的是 AutoSizer HOC-(大多数人都这样做)-那么我发现一种有用的模式是导出 2 个版本的组件 - 一个需要明确的宽度/高度属性,另一个用自动定尺器。伪代码是:

import { AutoSizer, VirtualScroll } from 'react-virtualized'

// Use this component for testing purposes so you can explicitly set width/height
export function MyComponent ({
  height,
  width,
  ...otherProps
}) {
  return (
    <VirtualScroll
      height={height}
      width={width}
      {...otherProps}
    />
  )
}

// Use this component in your browser where auto-sizing behavior is desired
export default function MyAutoSizedComponent (props) {
  return (
    <AutoSizer>
      ({ height, width }) => (
        <MyComponent
          height={height}
          width={width}
          {...props}
        />
      )
    </AutoSizer>
  )
}

【讨论】:

  • 有一件事我忘了提。我在使用 jsdom 的 node.js 中使用酶。 AutoSizer 是否依赖真实的 DOM 测量 api?
  • 这取决于getBoundingClientRectgetComputedStyle。你可以在这里看到它是如何衡量事物的:github.com/bvaughn/react-virtualized/blob/master/source/…
  • 好的,那么您建议绕过 AutoResizer 是最好的,因为 getBoundingClientRect 在 jsdom 中不准确。
  • 不应该把heightwidth(AutoSizer渲染回调的参数)传给MyComponent吗?
  • 你是救生员!
【解决方案2】:

把它放在我的测试用例中对我有用:

import { AutoSizer } from 'react-virtualized';

// ...

it('should do something', function() {
    spyOn(AutoSizer.prototype, 'render').and.callFake(function render() {
        return (
            <div ref={this._setRef}>
                {this.props.children({ width: 200, height: 100 })}
            </div>
        );
    });

    // do something...

我在这里使用 Jasmine 的 spyOn,但其他库有自己的覆盖函数的方法。 请记住,这对于将来对 react-virtualized 库的更改非常脆弱(this._setRef 刚刚从源代码中删除),并且可能会给您带来误报。

【讨论】:

  • 玩笑是这样做的:jest.mock('react-virtualized-auto-sizer', () =&gt; { return mockAutoSizer; }); 其中 mockAutoSizer 是您刚刚描述的功能。
【解决方案3】:

从 react-virtualized 9.12.0 开始,Autosizer 具有 defaultWidthdefaultHeight 属性。 我发现设置这些意味着酶测试运行正确 - 按预期呈现子行。

<AutoSizer disableHeight defaultWidth={100}>
    {({ width }) => (
  ....
  )}
</AutoSizer>

【讨论】:

  • 非常感谢!我不明白为什么console.log(wrapper.debug()); 没有显示任何行数据——只显示了标题。
猜你喜欢
  • 2017-04-26
  • 2018-09-01
  • 1970-01-01
  • 2019-07-16
  • 1970-01-01
  • 2022-06-30
  • 2017-05-29
  • 1970-01-01
  • 2017-06-28
相关资源
最近更新 更多