【发布时间】:2019-04-24 20:29:23
【问题描述】:
使用react-beautiful-dndhasn't been defined yet 测试组件的推荐方法。但是,这有点阻碍了我。
我可以使用react-beautiful-dnd 测试我的组件,方法是按照this recommendation 将它们包装在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 的组件?
【问题讨论】:
-
我可能误解了一些东西,但我不明白为什么你的模拟不起作用。我认为在
hoc中你会从模拟中返回props.children,而render prop是props.children() -
嗨@HermanStarikov。问题是,render prop 应该是一个包含
provided参数的函数,因为它会为children提供props。如果我按原样运行代码,则会收到错误消息:Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
标签: reactjs mocking jestjs react-beautiful-dnd