4

react-beautiful-dnd 尚未定义用于测试组件的推荐方法。但是,这有点阻碍了我。

我可以通过按照以下建议react-beautiful-dnd将它们包装起来来测试我的组件:DragDropContext

import React from 'react'
import {render} from 'react-testing-library'
import {DragDropContext} from 'react-beautiful-dnd'

import List from '../List'

describe('List', () => {

  it('renders', () => {
    const title = 'title'
    const {container, getByText} = render(
      <DragDropContext onDragEnd={() => {}}>
        <List>
          <li>{title}</li>
        </List>
      </DragDropContext>
    )
    expect(container.firstChild).toBeInTheDocument()
    expect(getByText(title)).toBeInTheDocument()
  })
})

然而,这似乎是一种次优方法。相反,我想模拟react-beautiful-dnd,但我不知道如何正确地做到这一点。

说,如果我的List组件是Droppable这样包装的:

return (
  <Droppable droppableId='id'>
    {provided =>
      <ListContainer 
        ref={provided.innerRef}
        {...provided.droppableProps}
      >
        {children}
        {provided.placeholder}
      </ListContainer>
    }
  </Droppable>
)

如何使用该render prop方法(哪个Droppable)为组件编写模拟?

jest.mock('react-beautiful-dnd', () => ({
  Droppable: props => props.children()
}))

以上适用于higher-order component. 如何将其更改为适用于实现render prop?

4

1 回答 1

20

react-beautiful-dnd通过实现以下内容,我能够模拟我们的库:

jest.mock('react-beautiful-dnd', () => ({
  Droppable: ({ children }) => children({
    draggableProps: {
      style: {},
    },
    innerRef: jest.fn(),
  }, {}),
  Draggable: ({ children }) => children({
    draggableProps: {
      style: {},
    },
    innerRef: jest.fn(),
  }, {}),
  DragDropContext: ({ children }) => children,
}));
于 2019-06-19T18:50:19.107 回答