我有一个使用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组件永远不会呈现。有什么想法吗?
发布于 2020-06-05 19:56:45
多亏了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组件现在正在呈现!
发布于 2021-10-29 20:16:55
或者,在全局设置中,您可以像这样定义jsDom属性:
// jsDom does not implement offset* methods. This will break tests
// for components that use react-virtualized-auto-sizer
// (https://github.com/jsdom/jsdom/issues/135#issuecomment-68191941)
Object.defineProperties(window.HTMLElement.prototype, {
offsetLeft: {
get: function () {
return parseFloat(window.getComputedStyle(this).marginLeft) || 0;
}
},
offsetTop: {
get: function () {
return parseFloat(window.getComputedStyle(this).marginTop) || 0;
}
},
offsetHeight: {
get: function () {
return parseFloat(window.getComputedStyle(this).height) || 0;
}
},
offsetWidth: {
get: function () {
return parseFloat(window.getComputedStyle(this).width) || 0;
}
}
});https://stackoverflow.com/questions/62214833
复制相似问题