Unit Testing Component - with Hook
Miteshdv opened this issue · comments
Cant Get Test Coverage of callback used in the component , any examples pls ?
Hi @Miteshdv
Thank you for the issue!
Could you provide some context, please?
At the moment we have https://github.com/xnimorz/use-debounce/blob/master/test/useDebouncedCallback.test.tsx for callback and https://github.com/xnimorz/use-debounce/blob/master/test/useDebounce.test.tsx for values.
You can find examples of testing components with these hooks inside these 2 files. The general piece of advice is to use stubs for timeouts and run them "to time" or run them all to test your components.
Thanks For Reply ,
I tried various ways , but i am getting error
ran 100000 timers, and there are still more! assuming we've hit an infinite recursion and bailing out
when i do jest.runAllTimers()
I have a component
const Time = ()=>{
debounced = useDebouncedCallback(()=>{
//CANT COVER THIS LINE IN TEST COVERAGE
console.log('test')
},500)
return <button onClick={debounced .callback}/>
}
i do
wrapper.find('button').prop('onClick')()
the callback function is not covered
i did
act(()=>{
jest.runAllTimers()})
i get error
I've made an example of your case, everything seems to work properly.
Here is the code, I hope It would help you to determine the problem: https://github.com/xnimorz/use-debounce/compare/tmp?expand=1#diff-f2501e1cc67f3029fe72847a2b1dba6abfeabf59289997bcdb06eed7ca3d8b11R13
Please, check your config and whether or not jest.useFakeTimers('modern');
is used
ok i managed to get it work using combination of jest.useRealTimers(), setTimeout and done.
no jest.runAllTimers() / jest.useFakeTimers('modern')
simply do
it('i am testing', done => {
wrapper.find('button').prop('onClick')()
setTimeout(()=>{
done()
},600)
})