如何使用函数作为 props 来测试 React 中的功能组件

问题描述 投票:0回答:1

我正在使用 Jest 测试功能组件,但是,当我将函数作为 props 传递时出现错误:

/..../src/pages/AddCommentComponent.tsx:43 props.updateCommentsHandler(); ^

TypeError:props.updateCommentsHandler 不是函数 在 updateCommentsHandler (/.../src/pages/AddCommentComponent.tsx:43:11)

知道如何在 render() 时指定 < AddCommentComponent />props.updateCommentsHandler 并测试该函数吗?其余测试正确并通过。

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,
      });
    });
  });

谢谢!

reactjs react-hooks jestjs react-testing-library
1个回答
0
投票

我找到了解决方案:

const updateCommentsHandler = jest.fn()
render(<AddCommentComponent updateCommentsHandler={updateCommentsHandler})
...
...
await waitFor(() => expect(axiosInstance.post).toHaveBeenCalledWith("/comments", {
        comment,
}));

expect(updateCommentsHandler).toHaveBeenCalled()
© www.soinside.com 2019 - 2024. All rights reserved.