我有一个使用react-virtualized AutoSizer的组件,并且在此组件内部有一个react-virtualized列表。呈现方式是:
<AutoSizer>
{({width, height}) => (
<List ref={(ref) => (this.refVirtualizedList = ref)}
width={width}
height={height}
playlistLoading={playlistLoading}
playlistPlayingTrackId={playlistPlayingTrackId}
rowCount={rowCount}
deferredMeasurementCache={this.cellMeasurerCache}
overscanRowCount={12}
scrollToIndex={trackGroupToGo - 1}
scrollToAlignment="center"
rowHeight={this.cellMeasurerCache.rowHeight}
updateTrackListFlag={updateTrackListFlag}
noRowsRenderer={this.renderNoRowsResult}
rowRenderer={this.renderTrackGroupRow}
onRowsRendered={this.handleOnRowsRendered} />
)}
</AutoSizer>
它运行完美,但不适用于测试。我看不到列表中的任何内容,并且从未调用函数rowRenderer
。我正在使用Jest和React测试库。当使用logDOM
方法检查组件内部时,我所看到的是:
<div
aria-label="grid"
aria-readonly="true"
class="ReactVirtualized__Grid ReactVirtualized__List"
role="grid"
style="box-sizing: border-box; direction: ltr; height: 0px; position: relative; width: 0px; will-change: transform; overflow-x: hidden; overflow-y: auto;"
tabindex="0"
/>
List组件从不呈现。有什么想法吗?
感谢GitHub上的这个问题:https://github.com/bvaughn/react-virtualized/issues/493
我要做的就是将测试设置为“模拟” AutoSizer的某些行为:
复制在问题中可以找到的相同解决方案:
describe("My Test", () => {
const originalOffsetHeight = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetHeight');
const originalOffsetWidth = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetWidth');
beforeAll(() => {
Object.defineProperty(HTMLElement.prototype, 'offsetHeight', { configurable: true, value: 50 });
Object.defineProperty(HTMLElement.prototype, 'offsetWidth', { configurable: true, value: 50 });
});
afterAll(() => {
Object.defineProperty(HTMLElement.prototype, 'offsetHeight', originalOffsetHeight);
Object.defineProperty(HTMLElement.prototype, 'offsetWidth', originalOffsetWidth);
});
// Your tests
})
List组件现在正在呈现!