javascript - 当存在于组件的 enzyme 渲染中时,“在 react 元素的 Prop 中找不到流动属性”

标签 javascript reactjs flowtype enzyme

我的组件:

// @flow
import React from 'react'

type Props = {
  close: Function,
  name: string
}

const MyComponent = ({ close, name }: Props) => (
  <div className='click' onClick={close}>
    {name}
  </div>
)

export default MyComponent

我的 enzyme 测试:

// @flow
import React from 'react'
import assert from 'assert'
import { shallow } from 'enzyme'
import sinon from 'sinon'

import MyComponent from 'client/apps/spaces/components/slideouts/record-settings/myc'

const defaultProps = {
  close: () => {},
  name: 'My Name'
}

const render = (props) => shallow(<MyComponent {...defaultProps} {...props} />)

describe('<MyComponent />', () => {
  it('renders the name', () => {
    const component = render()

    assert.equal(component.find('.click').text(), 'My Name')
  })

  it('calls close on Click', () => {
    const close = sinon.spy()
    const component = render({ close })
    const clickableDiv = component.find('.click')
    clickableDiv.simulate('click')

    assert(close.calledOnce)
  })
})

测试通过了,但它在我的“MyComponent”声明中给出了以下流程错误,它指的是我测试中的渲染行,尽管 name肯定是作为 defaultProps 的一部分传入的传入组件的对象:

property 'name' Property not found in props of react element 'MyComponent'

最佳答案

所以,如果我把第二个测试完全去掉,上面写的就没有流程错误了。

我认为问题在于,每当我将某些内容传递给测试文件中的 render() 时,flow 只检查组件上的重写 props,而不是所有的 props。

像这样重写我的测试渲染函数解决了我的问题:

const render = (overrideProps) => {
  const props = {
    ...defaultProps,
    ...overrideProps
  }

  return shallow(<MyComponent {...props} />)
}

关于javascript - 当存在于组件的 enzyme 渲染中时,“在 react 元素的 Prop 中找不到流动属性”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44980723/

相关文章:

javascript - 如何调用chrome扩展(全屏截图)或360浏览器的截图

javascript - 在传递给 useReducer 的 Props 发生更改后,React 更新 UI

javascript - 如何解决 Jest 模拟中的 Flow 类型错误

flowtype - 流量: resolving modules in a monorepo that uses Yarn workspaces

javascript - 带有 NativeScript 的 Facebook Flow(而不是 TypeScript)

javascript - 将鼠标悬停在没有包装器的样式组件上

javascript - Reactjs 和 masonry 布局 - 未定义

css - 在 React 中覆盖 CSS

javascript - 如何在 React Native 中访问文件系统?

javascript - 如何从表中获取输入值(无 ID)