首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Mocking react-beautiful dnd with Jest

Mocking react-beautiful dnd with Jest
EN

Stack Overflow用户
提问于 2018-11-22 15:51:05
回答 1查看 3.4K关注 0票数 3

使用react-beautiful-dnd hasn't been defined yet测试组件的推荐方法。然而,这在某种程度上阻碍了我。

我可以使用react-beautiful-dnd测试我的组件,方法是按照this recommendation将它们包装在DragDropContext

代码语言:javascript
复制
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中,如下所示:

代码语言:javascript
复制
return (
  <Droppable droppableId='id'>
    {provided =>
      <ListContainer 
        ref={provided.innerRef}
        {...provided.droppableProps}
      >
        {children}
        {provided.placeholder}
      </ListContainer>
    }
  </Droppable>
)

如何使用render prop方法( Droppable可以做到这一点)为组件编写模拟?

代码语言:javascript
复制
jest.mock('react-beautiful-dnd', () => ({
  Droppable: props => props.children()
}))

上面的方法适用于higher-order component。如何将其更改为适用于实现render prop的组件

EN

回答 1

Stack Overflow用户

发布于 2019-06-20 02:50:19

通过实现以下代码,我能够为我们的库模拟react-beautiful-dnd

代码语言:javascript
复制
jest.mock('react-beautiful-dnd', () => ({
  Droppable: ({ children }) => children({
    draggableProps: {
      style: {},
    },
    innerRef: jest.fn(),
  }, {}),
  Draggable: ({ children }) => children({
    draggableProps: {
      style: {},
    },
    innerRef: jest.fn(),
  }, {}),
  DragDropContext: ({ children }) => children,
}));
票数 18
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53426148

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档