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.
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. :)
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
getInstancefunction in that case:Most of the time you should just test the component the way it's used rather than relying on instances. :)