Reputation: 2081
I have a component that looks like:
const PersonalGreeting = (): ReactElement => {
const [date, setDate] = useState(new Date())
useEffect(() => {
const timer = setInterval(() => {
setDate(new Date())
}, 60000)
return () => {
clearInterval(timer)
}
}, [])
return (
<div>{date}></div>
)
}
I am getting into an error that states Jest: "global" coverage threshold for functions (89%) not met: 88.73%
and when I look at the logs, it says specifically my return ()
and clearInterval(timer)
in useEffect()
are not being tested. Here is a screenshot:
I honestly am pulling my hair out trying to figure out what they want me to test. Here is what I have tested:
describe('PersonalGreeting', () => {
const setTimeOfDay = jest.fn()
// eslint-disable-next-line
const useToggleMock: any = (initialState: string) => [
initialState,
setTimeOfDay
]
beforeEach(() => {
jest.spyOn(React, 'useState').mockImplementation(useToggleMock)
})
afterEach(() => {
jest.clearAllTimers()
})
it('renders component as expected', () => {
const wrapper = mount(
<TestWrapper>
<PersonalGreeting />
</TestWrapper>
)
expect(wrapper.text().length > 0).toBe(true)
})
it('Checks time every minute', () => {
jest.useFakeTimers()
mount(
<TestWrapper>
<PersonalGreeting />
</TestWrapper>
)
expect(setTimeOfDay).not.toBeCalled()
// 1 minute
jest.advanceTimersByTime(60000)
expect(setTimeOfDay).toHaveBeenCalledTimes(1)
})
})
Upvotes: 1
Views: 2054
Reputation: 4332
You need to unmount your component, this will fire the return function in your useEffect()
See docs
Something like this
it('Should unmount component', () => {
const wrapper = mount(
<TestWrapper>
<PersonalGreeting />
</TestWrapper>
)
wrapper.unmount();
// continue with your expect here
})
Upvotes: 3