使用react-testing-library测试react-window列表中的滚动

Alb*_*ing 12 reactjs react-testing-library react-window

我被困在这里进行一个测试,我想验证在滚动浏览由react-window导入的列表组件后,正在渲染不同的项目。该列表位于一个表格组件内,该组件保存了 React 上下文中的滚动位置,这就是我需要测试整个表格组件的原因。

不幸的是,滚动事件似乎没有效果,列表仍然显示相同的项目。

测试看起来像这样:

render(
  <SomeProvider>
    <Table />
  </SomeProvider>
)

describe('Table', () => {
  it('scrolls and renders different items', () => {
    const table = screen.getByTestId('table')

    expect(table.textContent?.includes('item_A')).toBeTruthy() // --> true
    expect(table.textContent?.includes('item_Z')).toBeFalsy() // --> true

    // getting the list which is a child component of table
    const list = table.children[0]

    fireEvent.scroll(list, {target: {scrollY: 100}})

    expect(table.textContent?.includes('item_A')).toBeFalsy() // --> false
    expect(table.textContent?.includes('item_Z')).toBeTruthy() // --> false
  })
})
Run Code Online (Sandbox Code Playgroud)

任何帮助将非常感激。

Emm*_*fon 1

react-testing-library默认情况下,您的组件会在 jsdom 环境中呈现,而不是在浏览器中。基本上,它只是生成 html 标记,但不知道组件的位置、滚动偏移量是多少等。

例如,请参阅此问题

可能的解决方案是:

  • 使用赛普拉斯
  • 或覆盖react-window用于测量容器中滚动偏移的任何本机属性(hacky)。例如,假设react-window正在使用container.scrollHeight:
// artificially setting container scroll height to 200
Object.defineProperty(containerRef, 'scrollHeight', { value: 200 })
Run Code Online (Sandbox Code Playgroud)