Background:
I've created a custom hook for useModal() to wrap some state for creating/destroying modals around the application:
import { useState } from "react";
export default function useModal(){
let [isShow, setIsShow] = useState(false);
let [modalTitle, setModalTitle] = useState("");
let [modalContent, setModalContent] = useState("");
const showModal = (title = false, content = false) => {
setIsShow(true);
if (title) setModalTitle(title);
if (content) setModalContent(content);
};
const hideModal = () => {
setIsShow(false);
setModalContent("");
setModalTitle("");
};
return { isShow, showModal, hideModal, modalTitle, modalContent };
};
The hook works perfectly fine when used around the application, but when trying to add some unit tests around it using Jest, it is throwing the following error when trying to access any of the returned items from the hook:
Invalid hook call. Hooks can only be called inside of the body of a function component
Here is the unit test:
import useModal from "./useModal";
import { renderHook, act } from "@testing-library/react-hooks";
describe("When modal is shown", () => {
it("IsShow should be true", () => {
const { result } = renderHook(() => useModal());
act(() => {
result.current.showModal("A title", "Some content");
})
expect(result.current.isShow).toBe(true);
});
});
Things tried:
All of my reading around this issue suggests that it is an issue with the way functional components mount, therefore, to install the @testing-library/react-hooks package which provides a wrapper to get around this issue
https://react-hooks-testing-library.com/usage/basic-hooks
Package versions used:
"@types/jest": "^27.4.0"
"@testing-library/jest-dom": "^5.16.2"
"@testing-library/react": "^12.1.2"
"@testing-library/react-hooks": "^7.0.2"
"react": "^17.0.2"
"react-dom": "^17.0.2"