用Jest嘲笑react-beautiful-dnd

时间:2018-11-22 07:51:05

标签: reactjs mocking jestjs react-beautiful-dnd

推荐使用react-beautiful-dnd enter image description here测试组件的方法。但是,这在某种程度上阻止了我。

我可以使用react-beautiful-dnd来测试我的组件,方法是按照hasn't been defined yet将它们包装在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的组件?

1 个答案:

答案 0 :(得分:1)

通过实施以下操作,我能够为我们的图书馆模拟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,
}));