I'm using a useFocusEffect() hook in my component, which uses refetch from react-query. Code is working fine in the app. Issue I'm facing is with unit testing. I'm using Jest and getting an error that TypeError: refetch is not a function.
I've defined a mock function const refetchFunc = jest.fn(); and have provided it to refetch as a mockReturnValue, but still the error persist.
App.js:
const { data, refetch } = useStudents(
student?.id
);
useFocusEffect(
React.useCallback(() => {
refetch();
}, [refetch])
);
Jest Test:
import { Home } from './Home';
jest.mock('hooks/Auth/useLoadAuthStudentsData', () => ({
useLoadAuthStudentData: jest.fn()
}));
jest.mock('hooks/Student/useStudents', () => ({
useStudents: jest.fn()
}));
jest.mock('@react-navigation/core', () => {
return {
...jest.requireActual('@react-navigation/core'),
useNavigation: jest.fn(() => ({}))
};
});
const useLoadAuthStudentsData = userHook as ReturnType<typeof jest.fn>;
const useStudents = tasksHook as ReturnType<typeof jest.fn>;
const navContext = {
isFocused: () => true,
addListener: jest.fn(() => jest.fn())
};
const mockParams = {
params: {
studentId: 'studentId'
}
};
describe('Home', () => {
beforeEach(() => {
const refetchFunc = jest.fn();
useStudents.mockReturnValue({
data: Student.deserializeAsList(studentsStub),
isLoading: false,
isSuccess: true,
isError: false,
refetch:refetchFunc
});
useLoadAuthStudentData.mockReturnValue({ data: studentStub });
});
const component = (
<NavigationContext.Provider value={navContext}>
<Home route={mockParams} navigation={{ goBack: jest.fn() }} />
</NavigationContext.Provider>
);
it('should render app without error', () => {
expect(render(component)).toBeTruthy();
});
Error:
● Home › should render screen without error
TypeError: refetch is not a function
54 | useFocusEffect(
55 | React.useCallback(() => {
> 56 | refetch();
| ^
57 | }, [refetch])
58 | );
59 |