reactjs - 开 Jest : How to test function that calls bind(this)

标签 reactjs jestjs

我有一个如下所示的父组件:

export class Header extends Component {
  constructor(props) {
    super(props)
    this.state = { activeTab: TAB_NAMES.NEEDS_REVIEW }
  }

  filterByNeedsReview() {
    const { filterByNeedsReviewFn } = this.props
    this.setState({ activeTab: TAB_NAMES.NEEDS_REVIEW })
    filterByNeedsReviewFn()
  }


  render() {
    return (
        ...
          <FilterTab
            ...
            onClick={this.filterByNeedsReview.bind(this)}
          />
          ...
    )
  }
}

我正在尝试测试 child 是否装载了正确的 Prop 。最初我将其作为匿名函数: onClick={ () => this.filterByNeedsReview() } 但我无法测试它,所以我尝试继续使用 bind(this) 相反。

但是,我在模拟 bind 函数时遇到问题:

  it('renders a filter tab with the right props for needs review', () => {
    const bounded = jest.fn()
    const boundedFilterByNeedsReview = jest.fn(() => {
      return { bind: bounded }
    })
    Header.prototype.filterByNeedsReview = boundedFilterByNeedsReview
    expect(
      shallowRender()
        .find(FilterTab)
        .findWhere(node =>
          _.isMatch(node.props(), {
            ... // other props
            onClick: bounded, //<-------------- FAILS WHEN I ADD THIS LINE
          })
        )
    ).toHaveLength(1)
  })

最佳答案

在构造函数中绑定(bind)该方法,以防止每次组件渲染时重新绑定(bind)该方法:

constructor(props) {
    super(props)
    this.state = { activeTab: TAB_NAMES.NEEDS_REVIEW }
    this.filterByNeedsReview = this.filterByNeedsReview.bind(this)
}

然后将绑定(bind)方法作为 prop 传递给子级:

<FilterTab
    ...
    onClick={this.filterByNeedsReview}
/>

您不需要在此处使用匿名函数。

关于reactjs - 开 Jest : How to test function that calls bind(this),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52961039/

相关文章:

javascript - 使用 Promises 从 DynamoDB 异步检索数据

vue.js - 来自@vue/test-utils的mount()和shallowMount()抛出TypeError : Cannot read property 'components' of undefined

reactjs - 与 Webpack react 不显示错误

react-native - 测试 Pressable 的按下状态

javascript - 类型错误:更新后无法读取未定义的属性 'any'

reactjs - 创建 react 应用程序错误

node.js - 在 express 应用程序中测试默认错误处理程序会导致超时

javascript - 在相对路径上开 Jest

javascript - Material-ui <SelectField> 项目未在 ReactJS 中显示

reactjs - 如何确认 Tree Shaking 是否适用于 Webpack 2?