React-testing-library: How to call component custom methods using react testing library

Created on 15 Apr 2020  路  3Comments  路  Source: testing-library/react-testing-library

I am using library to write test cases for my application. Actually i have some custom methods like sorting and formatting in my component. I want to call this methods using component instance But i didn't find any way to get the component instance from render.

Most helpful comment

Thanks @alexkrolick and @vdyachenko.

Please keep in mind that doing this is pretty irregular (use cases for useImperativeHandle are few and far between), but this is how you might go about it. Though I wouldn't bother with the getInstance function in that case:

const ref = React.createRef()
render(<MyComponent ref={ref} />)
ref.current.focus()

Most of the time you should just test the component the way it's used rather than relying on instances. :)

All 3 comments

Hello, @suresh777! You don't need to explicitly call your methods. Instead, try simulate the user behavior with this component:
For example, you're sorting table rows when user clicks on some button. Thus, to be able to test it you just need to simulate click on the button and check that you have a new order of your rows.

While what @vdyachenko said is what you need most of the time, sometimes elements have a public API (for developers!) exposed using instance methods on a class or useImperativeHandle on a function component.

In that case you can do something like this:

const getInstance = (Component, props) => {
  let instanceRef = { current: null }
  const InstanceWrapper = () => {
    return <Component {...props} ref={instanceRef} />
  }
  const renderResult = render(<InstanceWrapper />)
  return { ...renderResult, instanceRef }
}

const { instanceRef } = getInstance(MyComponent, { id: 'abc123' })
instanceRef.current.focus() // a common element-level API is .focus()

Thanks @alexkrolick and @vdyachenko.

Please keep in mind that doing this is pretty irregular (use cases for useImperativeHandle are few and far between), but this is how you might go about it. Though I wouldn't bother with the getInstance function in that case:

const ref = React.createRef()
render(<MyComponent ref={ref} />)
ref.current.focus()

Most of the time you should just test the component the way it's used rather than relying on instances. :)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

albert-olive picture albert-olive  路  3Comments

good-idea picture good-idea  路  4Comments

kangweichan picture kangweichan  路  3Comments

nagacoder picture nagacoder  路  3Comments

jalvarado91 picture jalvarado91  路  3Comments