react-virtualized 是否与 airbnb/enzyme 一起工作?

Does react-virtualized work with airbnb/enzyme?

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

这两个应该一起工作,是的。我认为可能的问题是 react-virtualized 组件的宽度或高度为 0,这导致它不渲染任何东西。 (它只渲染足以填充它的 "window"。)

假设您正在使用 AutoSizer HOC-(大多数人都这样做)- 我发现一种有用的模式是导出组件的 2 个版本- 一个需要显式 width/height 属性,一个需要包装另一个带有 AutoSizer。伪代码为:

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>
  )
}

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

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 刚刚从源代码中删除),并且可能会给您误报。

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

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