I have component and inside this component I have custom hook
const Component = () => {
const { open } = useHook()
return (
<div>
<button onClick={open}/>
</div>
)
})
Is there any chance to test that open callback that come from useHook has been called after button click in react testing library, something like this
it('Open function is called when we click button', () => {
render(Component)
fireEvent.click(getByRole('button'))
// How to test that open has been called?
expect(open).hasBeenCalledTimes(1)
})
It is easy to test when we pass function as props, but how to test in such case
CodePudding user response:
First of all your custom hooks must start with use, For example, useMyHook so that react can figure out a custom hook and apply hook-specific features to it
now you can figure out whether use callback has been called or not
let times = 0
const useMyHook = () => {
const use = () => {
times = 1
console.log("use function ran", times)
}
return (
{use: use}
)
}
CodePudding user response:
I'm not sure what you plan on doing with this information, but this would count the amount of times its been called and set it into state so you can use the info for whatever you need.
const Component = () => {
const { open } = myHook()
const handleClick = () => {
open()
console.log("open was called")
}
return (
<div>
<button onClick={handleClick}/>
</div>
)
})