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

Viewed 4961

I have a Parent component that looks like this:

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)}
          />
          ...
    )
  }
}

I'm trying to test that the child was loaded with the right props. Originally I had it as an anonymous function: onClick={ () => this.filterByNeedsReview() } but I couldn't test that so I tried to move on to bind(this) instead.

However, I'm having issues mocking out the bind function:

  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)
  })
1 Answers

Bind the method in the constructor to prevent the method from re-binding every time the component renders:

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

Then pass the bound method as a prop to the child:

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

You don't need to use an anonymous function here.

Related