我正在使用 Jest 测试函数组件,但是,当我将函数作为 props 传递时出现错误:
/..../src/pages/AddCommentComponent.tsx:43 props.updateCommentsHandler(); ^
TypeError:props.updateCommentsHandler 不是函数 在 updateCommentsHandler (/.../src/pages/AddCommentComponent.tsx:43:11)
知道如何在
props.updateCommentsHandler
时指定 render(<AddCommentComponent />)
并测试该功能吗?其余测试正确并通过。
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,
});
});
});
我找到了解决方案:
const updateCommentsHandler = jest.fn()
render(<AddCommentComponent updateCommentsHandler={updateCommentsHandler})
...
...
await waitFor(() => expect(axiosInstance.post).toHaveBeenCalledWith("/comments", {
comment,
}));
expect(updateCommentsHandler).toHaveBeenCalled()