I'm facing problem while testing a component that uses custom hook. I have written a custom hook for "Spinner" that internally uses a context to provide the spinner state to the components.
Then, I used useSpinner() inside, say for eg, Login form component. I'm getting the below mentioned error. (also the test didn't stop here and finally said all tests passed)
uncaught TypeError setLoading is not a function.
Login.tsx
...
const [loading, setLoading] = useSpinner();
const clearForm = useCallback(() => {
setEmail('');
setPassword('');
setLoading(false); /* Getting error here */
}, [setLoading]);
useEffect(() => () => clearForm(), [clearForm]);
...
use-spinner.tsx
export default function useSpinner(): SpinnerContextType {
const context = useContext(SpinnerContext);
if (!context) {
throw new Error('useSpinner is used outside of SpinnerContext scope');
}
return context;
}
In my types.ts file, I have defined the type SpinnerContextType
export type SpinnerContextType = [
loading: boolean,
setLoading: (value: boolean) => void
];
and SpinnerContext.tsx file contains
const SpinnerContext = createContext<SpinnerContextType>([false, null]);
In my test file Login.test.tsx, I have created a mock for this. But it didn't work.
const setLoadingMock = jest.fn((v: boolean) => {});
jest.mock('../../hooks/use-spinner', () => ({
__esModule: true,
default: [false, setLoadingMock],
}));
test('Test login', () => {
render(
<SpinnerContext.Provider value={[false, setLoadingMock]}>
<Login />
</SpinnerContext.Provider>
);
});