【问题标题】:Mocking react-beautiful-dnd with Jest用 Jest 模拟 react-beautiful-dnd
【发布时间】: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 propprops.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


【解决方案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,
}));

【讨论】:

  • 这应该是公认的答案。使用 Enzyme 的 mount 函数进行集成测试就像一个魅力!
猜你喜欢
  • 2022-11-24
  • 2019-03-19
  • 2020-05-05
  • 2020-04-04
  • 1970-01-01
  • 1970-01-01
  • 2020-09-02
  • 1970-01-01
  • 2022-01-26
相关资源
最近更新 更多