推荐使用react-beautiful-dnd
测试组件的方法。但是,这在某种程度上阻止了我。
我可以使用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
的组件?
答案 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,
}));