I'm testing a functional component with Jest, however, I get an error when I pass a function as props:
/..../src/pages/AddCommentComponent.tsx:43props.updateCommentsHandler();^
TypeError: props.updateCommentsHandler is not a functionat updateCommentsHandler (/.../src/pages/AddCommentComponent.tsx:43:11)
Any idea how I can specify the props.updateCommentsHandler when render(< AddCommentComponent />) and also test the function as well? The rest of the test is correct and passes.
AddCommentComponent.tsx:
const AddCommentComponent = (props: any) => { const [newComment, setNewComment] = useState<string>(); const onNewCommentUpdate = (e: React.FormEvent<HTMLTextAreaElement>) => { setNewComment(e.currentTarget.value); }; const updateCommentsHandler = () => { props.updateCommentsHandler(); }; const onSubmit = async () => { await axiosInstance.post("/comments", { post: newComment, }); updateCommentsHandler() }; return (<div><textarea aria-label="new-comment-box" placeholder="Enter your comment..." onChange={onNewCommentUpdate}> {newComment}</textarea><button aria-label="submit-button" disabled={false} onClick={onSubmit}> Submit</button></div> );};export default AddCommentComponent;
AddCommentComponent.test.tsx:
jest.mock("../libs/axios");describe("AddCommentComponent", () => { describe("when the user has entered a comment", () => { test("clicking submit should save the comment", () => { const comment = "Test comment"; render(<AddCommentComponent />); const commentInputBox = screen.getByLabelText("new-comment-box"); fireEvent.change(commentInputBox, { target: { value: comment } }); const submitButton = screen.getByRole("button", { name: "submit-button", }); fireEvent.click(submitButton); expect(axiosInstance.post).toHaveBeenCalledWith("/comments", { comment, }); }); });
Thanks!